In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.
A class is a blueprint or template for creating objects. It defines data members (variables) and member functions (methods). An object is an instance of a class.
A class is a user-defined data type, which holds its own data members and member functions that can be accessed and used by creating an instance of that class.
For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. The car can also accelerate, turn, apply brakes, etc. So here, the Car is the class, wheels, speed limits, and mileage are its attributes (data members) and accelerate, turn, apply brakes are its methods (member functions).
class ClassName {
// data members
// member functions
};
When a class is defined, only the specification (attributes and behaviour) for the object is defined. No memory is allocated to the class definition. To use the data and access functions defined in the class, we need to create its objects.
Objects are the actual entities that are created as an instance of a class. There can be as many objects of a class as desired. For example, in the above, we discussed the class of Cars. If we create an actual car based on the properties of the Car class, the car we made is the object of that class.
You create an object using:
ClassName objectName; // Object creation
#include <iostream>
using namespace std;
class Student {
public:
string name;
int age;
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Student s1;
s1.name = "Aarav";
s1.age = 20;
s1.display();
return 0;
}