The instance of a class in C++ is called an object. To allocate memory for the class we need to create an object for that class. We can access the members of the class using the dot (.
) operator.
class_name object_name;
The name of the class will replace the class_name
we want to create an object for, and object_name
will be any name we want to choose for the object.
If we want to access the member function print()
from the class using an object, we can do this by using object_name.print()
.
Objects can be accessed in two ways:
class_name *object_name = new class_name();
Here, the asterisk (*
) is used to declare the pointer and the new
keyword is used to allocate memory on the heap for the object.
We use the member access operator (->
) to access the member using a pointer to the object.
#include <iostream>using namespace std;class myClass{public:void demoObject(){cout<<"This function is accessed using an object."<<endl;}void demoPointer_to_object(){cout<<"This function is accessed using a pointer to the object."<<endl;}};int main() {myClass obj;myClass *obj1;obj.demoObject();obj1 = &obj;obj1->demoPointer_to_object();return 0;}
myClass.
myClass
.*obj1
.&
operator. Now when the object is updated, the pointer is also updated.obj1
to access the member function of the class.Free Resources