Pointers to Derived Classes:-
Polymorphism is also accomplished using pointers in C++. It allows a pointer in a base class to point to either a base class object or to any derived class object. We can have the following Program segment show how we can assign a pointer to point to the object of the derived class.
{
//Data Members
//Member Functions
};
class derived : public base
{
//Data Members
//Member functions
};
void main ( )
{
base *ptr; //pointer to class base derived obj ;
ptr = &obj ;//indirect reference obj to the pointer
//Other Program statements
}
For example, the following assignment statements are not valid
{
base obj;
derived *ptr;
ptr = &obja; //invalid.... .explicit casting required
//Other Program statements
}
A derived class pointer cannot point to base class objects. But, it is possible by using explicit casting.
{
base obj ;
derived *ptr;// pointer of the derived class
ptr = (derived *) & obj;//correct reference
//Other Program statements
}
Pointers to Derived Classes: Pointers can be declared to derived class.It can be used to access members of base class and derived class. A base class pointer can also be used to point to object of derived class but it can access only members that are inherited from base class.
#include<conio.h>
class base
{
public:
int a;
void get_a(int x)
{
a=x;
}
void display_a()
{
cout<<"In base"<<"\n"<<"a="<<a<<endl;
}
};
class derived:public base
{
int b; public:
void get_ab(int x,int y)
{
a=x; b=y;
}
void display_ab()
{
cout<<"In Derived "<<"\n"<<"a="<<a<<"\nb="<<b<<endl;
}
};
int main()
{
base b; base *bptr;
bptr=&b;//points to the object of base class bptr->get_a(100);
bptr->display_a();
derived d; derived *dptr;
dptr=&d;//points to the object of derived class
dptr->get_a(400);
dptr->display_a();
dptr->get_ab(300,200); dptr->display_ab();
bptr=&d;//points to the object of derived class bptr->get_a(400);
bptr->display_a();
return 0;
}
Output:
In base a=100
In base a=400
In Derived
a=300 b=200
In base
a=400
Read more :