Explain Pointer To Derived Classes With Example And Program in C++
Pointer to Derived Classes :-
1. They are declared as pointers along with the class name as the data-type.
2. To access the members of the class arrow symbol “->” is used.
3. Its observed that the pointer of Parent class can point towards the objects of its Child class. But a Child class pointer cannot point towards Parent class.
4. Its observed that if pointer of Parent class is assigned address of its Child class then also its cannot access the members of the Child class object, although it can access the Parent class members, in such situation we can access only those members which are inherited from the base class and not the members that originally belong to derived class.
5. Example :-
class Base
{
public:
void show()
{
cout<<"\i m base class function";
}
};
class Derive: public Base
{ int x;
public:
void show()
{ cout<<"\ni m derive class function";
}
void get()
{ cin>>x;}
void show1()
{ cout<<"\n x=”<<x;}
};
main()
{
clrscr();
Base b1;
Derive d1;
Base *bp;
bp=&b1;
bp->show(); //This Calls Class Base show()
bp=&d1;
bp->show(); //This also calls Class Base show() Not Class B show()
bp->get(); //error , get is not the member of Base
bp->show1(); //error
((Derive*) bp)->show(); // cast the pointer bp to the Derive type.
//This calls Class derive show() as bp is converted to Derive* type
getch();
}
Note: A derived class pointer can not point to the object of the Base class but it can point to the
objects of the same class.
In above example if we make an object of the derived class then.
main()
{
clrscr();
Base b1;
Derive d1,d2;
Derive *dp;
dp=&d1;
dp->show(); //This Calls Class Derive show()
dp->get();
dp->show1();
dp=&d2;
dp->show(); //This also calls Class Derive show() but for the object d2.
dp->get();
dp->show1();
dp=&b1; // error
((Base*) dp)->show(); // cast the pointer dp to the Base type.
//This calls Class Base show() as dp is converted to Base* type
getch();
}
Labels: C++