C++ pointer to derived class
Pointer to objects of the base class are type compatible with the pointers to objects of a derived class. Therefore a single
pointer variable can be made to point to the objects belonging to different classes lets see in Example
if B is a base class and D is a derived class from B , Then a pointer declare as a pointer to B can also be a pointer to D.
consider the following declarations
B *cptr;
B b;
D d;
cptr=&b;
|
we can make in the above example cptr to point to the object d as follows
cptr=&d;
This is perfectly valid with c++ language because d is an object derived from the class B
however these is a problem in using cptr to access the public of the derived class D. using cptr we can access only those members which are inherited from B and not the member that originally belongs to D. in case a member of D class has the same name as one of the members of class B, then any reference to that member by cptr variable will always access the base class member.
Althought c++ language permits a base pointer to point to any object derived from the base the pointer cannot be directly used to access all the members of the derived class. we may have to use another pointer declared as pointer to the derived type.
let us take example of how pointers to a derived object are used
POINTER TO DERIVED OBJECTS
<iostream>
using namespace std;
class BC
{
:
b;
show()
{
cout << "b=" << b << "\n";
}
};
class DC: public BC
{
:
d;
show()
{
cout << "b=" << b << "\n";
cout << "d=" << d << "\n";
}
};
main()
{
BC *bptr;
BC base;
bptr=&base;
bptr->b=100;
cout << "bptr points to base object \n";
bptr->show();
//derived class
DC derived;
bptr=&derived;
bptr->b=200;
cout << "bptr now points to derived object \n";
bptr->show();
DC *dptr;
dptr=&derived;
dptr->d=300;
cout << "dptr is derived type pointer \n";
dptr->show();
cout << "using ((DC*)bptr)\n";
((DC*)bptr)->d=400;
((DC*)bptr)->show();
}
|
output:
bptr points base object
b=100
bptr now points to derived object
b=200
dptr is derived type pointer
b=200
d=300
using((DC?)bptr)
b=200
d=400
|
Note: we have used the statement
bptr->show();
so two times first when bptr points to the base object, and second when bptr is made to point to the derived object. but both the times, it executed BC::show() function and displayed the content of the base object. How ever the statements
dptr->show();
((DC *)bptr)->show();
Display the contents of the derived object. This shows that, although a base pointer can be made to point to any number of derived objects, it cannot directly access the members defined by a derived class.