Write a C++ program to illustrate ‘this’ pointer and pointers to derived classes.




#include<iostream.h>
#include<conio.h>
class BC
{
public:
int b;
void show()
{
cout<<"b= "<<b<<endl;
}
BC findlarge(BC obj)
{
if(b>obj.b)
return *this;
else
return obj;
}
};
class DC:public BC
{
public:
int d;
void show()
{
cout<<"b= "<<b<<endl;
cout<<"d= "<<d<<endl;
}
};
int main()
{
clrscr();
BC b1,b2;
b1.b=10;
b2.b=20;
BC Large=b1.findlarge(b2);
cout<<"\n Largest is :";
Large.show();
BC *bptr;
BC base;
bptr=&base;
bptr->b=100;
cout<<"Base pointer to base class\n";
bptr->show();
DC derived;
bptr=&derived;
bptr->b=200;
cout<<"Base pointer to base class\n";
bptr->show();
DC *dptr;
dptr=&derived;
dptr->d=300;
cout<<"Derived pointer to derived class\n";
dptr->show();
((DC*)bptr)->d=400;
cout<<"Type conversion\n";
((DC*)bptr)->show();
getch();
return 0;
}




Output of the above program is:
Largest is :b= 20
Base pointer to base class
b= 100
Base pointer to base class
b= 200
Derived pointer to derived class
b= 200
d= 300
Type conversion
b= 200
d= 400

Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: