user3227126
user3227126

Reputation: 239

The reason why baseclass pointer cannot be assigned to derived class pointer

Can any explain why baseclass pointer cannot be assigned to derived class pointer? I know it is not possible ,but i like to know the reason .logically derived class contain base class.Let me know the reason Thanks in advance

Upvotes: 2

Views: 276

Answers (3)

ravi
ravi

Reputation: 10733

I assume your question is why following should not be done:-

Derived *ptr = new Base;   //assume for now public inheritance.

Derived is specialization of Base i.e Derived would inherit all features of base plus it could also add some of its own features. That means assigning Base to Derived ptr leads to loss of those features which could result into undefined behavior if call is made to that variable/method.

Upvotes: 0

zachyee
zachyee

Reputation: 346

A derived class can have its own data members and member functions in addition to all of those within the base class.

If you point the derived class pointer to the same thing as a base class pointer, the derived class pointer will think it's pointing to a derived class object, even though it's pointing to a base class object.

If you try to access derived class data members or member functions using this derived class pointer, it won't work because it's pointing to a base class object that doesn't have these capabilities.

For instance, let's assume I have a base class called Person and a derived class called Programmer. I can make a Person object and have a pointer point to that object. I can then try to make a Programmer pointer point to that Person object as well (by setting it equal to the Person pointer). If I used my Programmer pointer to try and make the Person object code (equivalent to calling a Programmer member function) or do something only a Programmer does, it wouldn't work because the Person hasn't been specialized.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206607

Consider:

struct A
{
};

struct B : A
{
   int b;
};

struct c : A
{
   char c;
};

C cobj;
A* aptr = &cobj;
B* bptr = aptr; // Assuming this were allowed...
bptr->b = 10;

By doing that you'd have used memory beyond what is valid. You have created an object of size sizeof(C) but not you are treating it like it is of size sizeof(B).

Upvotes: 1

Related Questions