Pointer to Object


In C++ you can declare a pointer that contains the address of the object of type class.
Suppose we have created a class named base as shown below:
class Base
{
public:
int x;
void display ()
{
cout<<"X="<<x<<endl;
}
};

Now you can declare a pointer that contains the address of the object of class base as shown below:
Base *ptr; // declare a pointer of base class
Base B1; // declare an object of base class
Ptr = &B1; // assign address of object b1 to base class pointer

Using this pointer you can access the public member of the base class as shown below:
ptr->x = 10;
ptr->display ();

     

#include <iostream.h>
class Base
{
public:
int x;
void display ()
{
cout<<"X="<<x<<endl;
}
};
int main ()
{
Base B1;
Base *ptr;
ptr = &B1;
ptr->x = 10;
ptr->display();
}
Output:
X= 10

Download Projects


Download Programs