Classes and Objects
A class is a user-defined blueprint from which objects are created. It groups data members and member functions under a single name.
Defining a Class
Use the class keyword. Members are private by default.
Use access specifiers public: and private: to control visibility.
Creating Objects
Instantiate a class just like a variable. Access members with the dot operator.
#include <iostream>
using namespace std;
class Car {
public:
string brand;
string model;
int year;
void display() {
cout << year << " " << brand << " " << model << "\n";
}
};
int main() {
Car car1;
car1.brand = "Toyota";
car1.model = "Corolla";
car1.year = 2022;
car1.display();
return 0;
}
Try it Yourself โ