A base class pointer can point to a derived class object, but vice versa in not true | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

A base class pointer can point to a derived class object, but vice versa in not true

A derived class object should have information about contents of base class even then a pointer of derived class cannot point to object of base class. But instead a pointer of base class can point to derived class. Why so ? Can u explicitly change this behaviour ,if so then how ?

15th Sep 2018, 7:29 AM
AKSHAT BHATT
AKSHAT BHATT - avatar
5 Answers
+ 3
In C/C++, you can make a pointer point to any memory location as you want, using explicit type casting. This means you can let a pointer (derived object type) point to its base object also. But whether you can do something useful with this pointer is another story. So, in term of class' methods usage, when you declare a pointer of class X, you usually expect that you can call all the exposed methods of X thru the pointer, as the compiler have knowledge about X and will arrange the code to do so. Now, we already know that derived object is also (contains) base object, so base object pointer (which points to derived object) can call the base methods as the memory layout of the base object part is known the compiler. If we let the derived object pointer point to its base object, base object is surely not a derived object, so you can't call the derived methods with this pointer. So, normally, we should not point a derived object pointer to its base object.
16th Sep 2018, 7:35 AM
Rocky Lee
Rocky Lee - avatar
+ 2
Suppose following structure : Class A { member1, member2 } Class B extends/inherits B { member3, member4 } A object1=new A() ; A objectA=new B() ; (X) B objectB=new B() ; B object2=new A() ; Here pointer of class B can point to address where all members are stored but pointer of class A can not point to such address that has all members. You can do this by explicitly tyoecasting with data loss.
15th Sep 2018, 9:37 PM
Jai Verma
Jai Verma - avatar
+ 1
Because derived class has all data of base class (by definition) then compiler can access to all member of derived like base but opposite is not true because derived can add members not avaible in base class.
15th Sep 2018, 8:19 AM
KrOW
KrOW - avatar
0
Ina u mean to say.. Q) why don't we make a pointer of derived class instead of base class. Ans) due to resource wastage. Is that right ?
15th Sep 2018, 9:54 AM
AKSHAT BHATT
AKSHAT BHATT - avatar
0
Ina I asked the same question in different words.
15th Sep 2018, 2:26 PM
AKSHAT BHATT
AKSHAT BHATT - avatar