Defining a Class
The class keyword. It acts as a container for data (attributes) and functions (methods).
class Car {
public: // We'll discuss this next
// Attributes (member variables)
std::string brand;
std::string model;
int year;
};Access specifiers define how the members (attributes and methods) of a class can be accessed.
public: Members are accessible from outside the class.
private: Members cannot be accessed from outside the class. This is the default if not specified.
class BankAccount {
private:
// This data is safe and cannot be
// changed directly from outside.
double balance;
public:
// This function is public, so it
// can be called from outside.
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
};Creating an Object
Called instantiation. You can create an object by declaring a variable of the class type, just like any other variable type (e.g., int, string). Access its public members using the dot operator (.).
// Create an object (instance) of the Car class Car myCar; // Access and set its public attributes myCar.brand = "Ford"; myCar.model = "Mustang"; myCar.year = 1969;
Class Methods
Functions that belong to a class. They define the behavior of an object and can access its attributes.
class Car {
public:
std::string brand;
std::string model;
int year;
// A public method
void printInfo() {
std::cout << brand << " " << model
<< " (" << year << ")";
}
};Use the dot operator (.) to call its public methods.myCar.printInfo();
Constructors
Special method that is automatically called when an object is created. It’s perfect for initializing attributes. It has the same name as the class and has no return type (not even void).
This constructor for the Car class takes arguments to initialize its attributes right when the object is created.
class Car {
public:
std::string brand;
std::string model;
int year;
// The Constructor
Car(std::string b, std::string m, int y) {
brand = b;
model = m;
year = y;
}
};Now, you can create and initialize an object in a single, clean line of code.
// Create a Car object using the constructor
Car myCar("Ford", "Mustang", 1969);
Car yourCar("Honda", "Civic", 2022);
// This is much cleaner than setting each
// member variable one by one!
// myCar.brand is already "Ford"
// myCar.model is already "Mustang"
// myCar.year is already 1969Encapsulation: Getters and Setters