Classes in Cpp
Classes in Cpp
Eman Beshr
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.
C++ Class
In C++, class is a group of similar objects. It is a template from which objects are created. It can
have fields, methods, constructors etc.
#include <iostream>
using namespace std;
class ScholarHat {
public: // Public access specifier
int x; // Public attribute
int main() {
ScholarHat myObj;
myObj.x = 70;
myObj.display();
return 0;
}
Classes in C++ Eng. Eman Beshr
C++ Constructor
In C++, constructor is a special method which is invoked automatically at the time of object
creation. It is used to initialize the data members of new object generally. The constructor in C++
has the same name as class or structure.
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined
only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed with
a tilde sign (~).
Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.
C++ Constructor and Destructor Example
Let's see an example of constructor and destructor in C++ which is called automatically.
Classes in C++ Eng. Eman Beshr