Pointers can be used to point to the base class objects and objects of derived class. Pointers to objects of base class are compatible with pointers to objects of a derived class. Single pointer variable can be made to point objects belonging to different classes. If B is base and D is derived class then pointer declared as a pointer to B can also be a pointer to D.
Example:
B *cptr; // pointer to of class
B b; //Base object
D d; // Derived object
cptr=&b; //cptr store address of object b of base class
cptr=&d; //cptr store address of object d of derived class
It's not possible to access the public members of the derived class D by using cptr.Using base class pointer to object cptr, only those members inherited from B can be accessed and not the members that originally belong to D. For a member of D has the same name as any of the member of B, then reference to that member by cptr will always access the base class member. While C++ allows a base pointer to point to any object derived from that base, the pointer cannot be directly used to access all the members of the derived class.
Example:
#include<iostream.h>
#include<conio.h>
class base
{
int a;
public:
void get()
{
cout<<"\nEnter a value for A";
cin>>a;
}
void put()
{
cout<<"\nThe Value for A "<<a;
}
};
class derived : public base
{
int a;
public:
void get()
{
cout<<"\nEnter a value for A";
cin>>a;
}
void put()
{
cout<<"\nThe Value for A "<<a;
}
};
void main()
{
base *bptr,b;
derived d;
clrscr();
cout<<"\nPointing to the base class ";
bptr=&b;
bptr->get();
bptr->put();
cout<<"\nPointing to the derived class ";
bptr=&d;
bptr->get();
bptr->put();
getch();
}