Pointer to Derived Class 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 address of the base class object 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 to base class pointer
Using this pointer you can access members of the base class as shown below:
ptr->x = 10;
ptr->display ();
Now derived a new class named Derive from base class as shown below:
class Derive: public Base
{
public:
int y;
void display ();
{
cout<<”X=”<<x<<endl;
cout<<”Y=”<<y<<endl;
}
};
C++ allows you to assign the address of the derived class object to the base class pointer as shown below:
Derive D1; // declare an object of derived class
ptr = &D1; // assign address of derive class object to base class pointer.
Now if you try to access the member of derived class using base class pointer it will not allow you to access the member of derived class as shown below:
ptr->y = 20; // It will generate an error
ptr->display (); // It will invoke the display() of base class
Thus to overcome this problem you have to declare a pointer of derived class and then assign the address of derived class object to this pointer as shown below:
Derive *ptr1;
Derive D1;
*ptr1 = &D1;
ptr1->y = 20;
ptr1->display (); // it will invoke the display () of derived class.
Thus in order to access member of particular class you need to create a pointer of that class and then assign the address of that class object to the pointer.

#include <iostream.h>
class Base
{
              public:
              int x;
              void display ()
              {
                        cout<<”X=”<<x<<endl;
              }
};
class Derive: public Base
{
              public:
              int y;
              void display ();
              {
                        cout<<”X=”<<x<<endl;
                        cout<<”Y=”<<y<<endl;
              }
};
int main ()
{
              Base B1;
              Base *ptr;
              ptr = &B1;
              ptr->x = 10;
              ptr->display();
              Derive D1;
              Derive *ptr1;
              ptr1 = &D1;
              ptr1->x = 10;
              ptr1->y = 20;
              ptr1->display ();
}

Output:
X= 10
X = 10
Y = 20

Download Projects


Download Programs