26.8.15

Write a C++ program to illustrate ‘this’ pointer

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********************************

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

No comments:

Post a Comment

Comment Here