Classes and Objects
In C++, classes are used to define objects. A class is a blueprint that defines the properties and behaviors that an object of that class will have.
To define a class in C++, you can use the class
keyword followed by the name of the class.
TEXT/X-C++SRC
1// Class definition
2
3class Car {
4 // Class members
5};
The class can have attributes (properties) and methods (functions).
TEXT/X-C++SRC
1// Class definition
2
3class Car {
4 // Attributes
5 string brand;
6 int year;
7
8 // Methods
9 void start() {
10 cout << "Starting the car" << endl;
11 }
12};
To create an object of a class, you can use the class name followed by the object name and optional parentheses.
TEXT/X-C++SRC
1// Create an object of the Car class
2class Car myCar;
Once you have created an object, you can access its attributes and call its methods using the dot operator.
TEXT/X-C++SRC
1// Access the attributes and methods of the object
2myCar.brand = "Toyota";
3myCar.year = 2020;
4
5myCar.start();
xxxxxxxxxx
18
using namespace std;
// Define the `Car` class
// Class definition
// constructors
// methods
int main() {
// Create an object of the `Car` class
// Access the methods and properties of the object
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment