Salta al contenuto
Note per Studenti Introduction to C++ Classes Report

Introduction to C++ Classes

In questa pagina 6

A class is a user-defined data type that acts as a blueprint for creating objects. It encapsulates data members (variables) and member functions (methods) operating on the data: this is the basis of encapsulation and object-oriented programming (OOP). It is the C++ counterpart of the struct + functions of C (see the structs notes of this course).

Term Meaning
Encapsulation bundling data and methods together
Data members variables holding the data of the class
Member functions functions operating on the data members
Object instance of a class, created from the blueprint
Access specifiers control the visibility of members

Defining a class

Use the class keyword:

cpp
class ClassName {
public:
    // Public members (accessible from outside the class)
    int publicVar;
    void publicMethod() {
        // Code for the method
    }
private:
    // Private members (accessible only within the class)
    int privateVar;
    void privateMethod() {
        // Code for the method
    }
protected:
    // Protected members (accessible within the class and derived classes)
    int protectedVar;
};
Specifier Accessible from
public outside the class too
private only within the class
protected the class and its derived classes

Creating and using an object

cpp
ClassName obj; // Creates an object of type ClassName

Public members are reached with the dot operator ..

cpp
#include <iostream>
using namespace std;
class Car {
public:
    // Data members
    string brand;
    int year;
    // Member function
    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};
int main() {
    Car car1; // Create an object of the Car class
    car1.brand = "Toyota";
    car1.year = 2020;
    car1.displayInfo(); // Call the member function
    return 0;
}

Output: Brand: Toyota, Year: 2020

Constructor and destructor

  • Constructor: special function called automatically when an object is created; used to initialize it.
  • Destructor: special function called automatically when an object is destroyed; defined as ~ClassName().
cpp
class Car {
public:
    string brand;
    int year;
    // Constructor
    Car(string b, int y) {
        brand = b;
        year = y;
    }
    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

Usage: Car car1("Toyota", 2020);

(The slides show only the ~ClassName() syntax for destructors, no full example.)

Inheritance

A class can inherit members from another with the : operator.

cpp
class Vehicle {
public:
    string type;
};
class Car : public Vehicle {
public:
    string brand;
};

Car has its own brand plus the members of Vehicle (here type).

Example: encapsulation with a private state

cpp
#include <iostream>
using namespace std;
class BankAccount {
private:
    string accountHolder;
    double balance;
public:
    // Constructor
    BankAccount(string name, double initialBalance) {
        accountHolder = name;
        balance = initialBalance;
    }
    // Member functions
    void deposit(double amount) {
        balance += amount;
        cout << "Deposited: $" << amount << endl;
    }
    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
            cout << "Withdrawn: $" << amount << endl;
        } else {
            cout << "Insufficient funds!" << endl;
        }
    }
    void displayBalance() {
        cout << accountHolder << "'s Balance: $" << balance << endl;
    }
};
int main() {
    BankAccount account("John Doe", 500.0);
    account.displayBalance();
    account.deposit(150.0);
    account.withdraw(100.0);
    account.displayBalance();
    return 0;
}

Output: balance 500, deposited 150, withdrawn 100, final balance 550 (the data members are private, so they can only be changed through the member functions, which check the withdrawal).

Key features

  • Encapsulation: data and functions bundled together.
  • Abstraction: hides implementation details.
  • Inheritance: reuse of code.
  • Polymorphism: functions can be defined in multiple forms.

Versione ripasso

Introduction to C++ Classes

  • A class is a blueprint of data members and member functions; an object is an instance, ClassName obj;. Public members are reached with ., e.g. car1.brand.
cpp
class Car {
public:
    string brand;
    void displayInfo() { cout << brand << endl; }
};
  • class Name { public: ... private: ... protected: ... };: note the final ;. public is visible everywhere, private only inside the class, protected also in derived classes.
  • Constructor (same name as the class) runs at creation: Car car1("Toyota", 2020);. Destructor ~ClassName() runs at destruction.
  • Inheritance: class Car : public Vehicle { ... }; adds the members of Vehicle to Car.
  • Encapsulation: BankAccount keeps balance private and changes it only through deposit and withdraw, which refuses when amount > balance ("Insufficient funds!"). Final balance of the example: 500 + 150 - 100 = 550.
  • Pillars: encapsulation, abstraction, inheritance, polymorphism.
  • Typical errors: accessing a private member from main, forgetting ; after the class.