CodeClerks

POINTERS TO DERIVED CALSSES IN C++



Write the reason you're deleting this FAQ

POINTERS TO DERIVED CALSSES IN C++

We can use pointers not only to the base objects but also to the objects of derived classes.
Pointers to objects of a base class are type-compatible with pointers to objects of a derived class. Therefore, a single pointer variable can made to point to objects belonging to different classes. For example, if B is a vase class and D is a derived class from B, then a pointer declared as a pointer to B can also be a pointer to D. Consider the following declarations:

B *cptr; // pointer to class B type variable
B b; // base object
D d; // cptr points to object b


We can make cptr to point to the object d as follows;
cptr = &d; //cptr points to object d

This is perfectly valid with C++ because d is an object derived from the class B.
However, there is a problem in using cptr to access the public members of the derived class D. Using cptr, we can access only those members which are inherited from B and not the members that originally belong to D. In case a member of D has the same name as one of the members of B, then any reference to that member by cptr will always access the base class member.

Although C++ permits 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. We may have to use another pointer declared as pointer to the derived type.


#include

using namespace std;

class BC
{
   public:
        int b;
        void show()
        { cout

Comments

Please login or sign up to leave a comment

Join