Pointers to Derived Classes

Hello friends, Hope you all doing good. This is the my first attempt to write an article on medium so if i do any mistake please forgive me for that. So let’s Start

We know we can use pointers for base objects, We can also use it to the object of derived classes. Pointer to object of base class are type-compatible with pointer to object of derived class. Therefore, a single pointer variable can be made to point to object belongings to different classes.

For Example: B is a base class and D is a derived class from B

B *bptr;
B b;
D d;
bptr = &b

// We can make bptr to point to the object d as follow

bptr = &d

This is valid with c++ because d is an object derived from B

But, There is a problem using bptr to access the public member of the derived class D, Using pointer bptr we can only access those members which are inherited from base class B and not the member that originally belong to D. In case a member of D has the same name as one of the member of B then any reference to that member by bptr will always access the base class member.

Although C++ permits a base pointer to point any object derived from that base, The pointer can not be directly used to access all the member of the derived class we may have to use another pointer declared as pointer to the derived type.

Class BC{

int b;
void show();
{cout << "b= " << b << "\n";}

Class DC: public B{

int d;
void show();
{cout << "b= " << b << "\n"
cout << "d= " << d << "\n";}


int main(){

BC *bptr;
BC base;
bptr = &base; // pointing to base object

bptr ->b = 100;
cout << "bptr points base object \n";
bptr -> show(); // Show of base class

//Derived Class
DC derived;

bptr = &derive; // Now bptr pointing to derived class DC
bptr -> b = 200; // Set b of baseclass using derived class pointer

// bptr -> d = 300;
//Above line wont work as the pointer is created for base if we want to use it like this we need to do type conversation which we will show //later in this example

cout << "bptr now points Derive object \n";
bptr -> show(); // Show of base class

DC *dptr;
dptr = &derived
dptr -> d = 300;

cout << "dptr is derived type pointer \n";
dptr -> show(); // This will call the show of derive class

//Now how to access derived class method and object using base class

cout << "using ((DC *) bptr) \n";
((DC *) bptr) -> d =400; //This is now possible
((DC *) bptr) -> show(); //This will call derives show

return 0;


((DC *) bptr) this sentence cast base class pointer bptr to DC type and using it we can able to call derived class member and function using base class pointer.

We can also able to call derived class function using Virtual function if we declare the function as virtual in base class then we are able to call the same name function from derived class.

So, That’s it for today topic Happy learning!

Passionate about learning