Explain pointer to derived classes in c++

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.

class base
{
//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
}

The pointer ptr points to an object of the derived class obj. But, a pointer to a derived class object may not point to a base class object without explicit casting.

For example, the following assignment statements are not valid 

void main ( )
{
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.

 void main ( )
{
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<iostream.h>
#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 :

1. Constructor and destructor in C++

2. Explain fifth generation of Computers.

Md Ashraf

'KNOWLEDGE WITH ASHRAF' is the platform where you find all the type of knowledge especially on programming based. Our goal is to give you a deeper grasp of technology in specifics that will help you increase your knowledge.

Previous Post Next Post

Contact Form