A Base Class pointer can point to a derived class object. Why is the vice-versa not true without casting? Logically a base class would not have enough information of the derived class but a derived class should have the information of the base class as well. I am missing some basics here.
13 Answers
If I tell you I have a dog, you can safely assume that I have a pet.
If I tell you I have a pet, you don't know if that animal is a dog, it could be a cat or maybe even a giraffe. Without knowing some extra information you can't safely assume I have a dog.
similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.
(The creaking you will now hear is the analogy stretching)
Suppose you now want to buy me a gift for my pet.
In the first scenario you know it is a dog, you can buy me a leash, everyone is happy.
In the second scenario I haven't told you what my pet is so if you are going to buy me a gift anyway you need to know information I haven't told you (or just guess), you buy me a leash, if it turns out I really did have a dog everyone is happy.
However if I actually had a cat then we now know you made a bad assumption (cast) and have an unhappy cat on a leash (runtime error).
-
12+1: Best answer so far, IMHO. A simple analogy that intuitively illustrates the problem. – Oliver Charlesworth Feb 08 '11 at 19:43
-
4"For every problem there is one solution which is simple, neat, and wrong." — H.L. Mencken. Intuitive answers often fall into this category, especially OO described in "real-world" terms. Sometimes a base class pointer does point to an object of derived class type and that is why (as the question points out) you can cast. – Fred Nurk Feb 08 '11 at 20:05
-
1@Fred: The answer isn't wrong; it is never valid to point at a base-class *object* with a pointer-to-derived. As you say, though, it is sometimes valid to cast a base-class *pointer* to a pointer-to-derived. – Oliver Charlesworth Feb 08 '11 at 20:37
-
3A dog is an animal, but an animal is not necessarily a dog, it might be a giraffe. What does this analogy tell? If Animal is considered to be the base class and Dog/Giraffe are the derived classes.Since Dog/Giraffe are indeed animals i.e the child class should be able to point to the base class? Should that not be the case? – Zuzu Feb 09 '11 at 11:32
-
1yes if you are casting then you are explitly telling the compiler to shut up cos you have extra information it doesn't. I think I can expand the animal metaphor to add the pointers and casting in a bit - bear with me – jk. Feb 09 '11 at 13:34
-
1I think you'd be better off describing how you can't call a child's method on a base class. You have a chair with armrests (ArmRestChair) that derives from a chair that doesn't have armrests (Chair). In this case Chair is a valid object (in your example the base class is abstract). You put a chair's address into an ArmRestChair pointer. The user comes along and tries to rest his arms on the ArmRestChair, and he just faulted on a paradox.... (his arms fall to the ground and he gets hurt banging on the side of the chair). – Lee Louviere Feb 09 '11 at 19:27
-
You could also put a MobileChair into an ArmRestChair pointer. The user tries to sit in the ArmRestChair, but because he didn't know it's a MobileChair, the chair starts moving on him. – Lee Louviere Feb 09 '11 at 19:29
-
@jk the analogy is wrong. base class here is animal and derived class is dog. so how can i use animal type pointer to point to dog as i dont know what animal one hass. – Vishwanath gowda k Sep 24 '14 at 08:29
-
1I have never laughed reading an explanation to a technical question. This time I did :) . Great answer. – Mathai Oct 07 '16 at 00:20
-
Any use of Base Class pointer pointing to a derived class object? If we access overridden function, function in base class is called and not the overridden function of derived class. Instead we could as well use pointer to derived class object itself right? – Rajesh Sep 26 '17 at 15:44
-
I knew exactly what the OP wanted, then I read this analogy now my brain hurts. I like @billlynch answer better – simplename Apr 13 '21 at 05:18
-
@OliverCharlesworth __1__ but why there is necessary of this `explicit base to derived conversion` and `implicit derived to base conversion` – Abhishek Mane May 10 '21 at 12:03
-
@OliverCharlesworth __2__ and after doing `explicit base to derived conversion` if I try to access derived class data through this `ptr` it gives random output, sometime it cause runtime errors, is it all part of `Undefined Behavior` right ? – Abhishek Mane May 10 '21 at 12:04
We have two objects.
class A {
int a;
};
class B : A {
int b;
};
Allocate an instance of B
. We can interface with that as either an A*
or a B*
.
Allocate an instance of A
. If we were to cast it to a B*
, should there be space allocated for the member b
?

- 80,138
- 16
- 128
- 173
-
1This! This helped me clear my doubt of WHY it isn't allowed in a TECHNICAL way. Thanks. – Sumaiya A Apr 10 '21 at 10:22
-
@BillLynch `B b1;` `A *pa;` declaring object of B and ptr of object A, Now we have to __cast__ it like this `pa=(A*)&b1;` or we can use direct `pa=&b1;` ? – Abhishek Mane May 10 '21 at 07:02
Uh, because the base class is not a derived class.
When you have a valid pointer to a type, then you are saying that the object pointed to will have certain data in certain locations so that we can find it. If you have a pointer to a derived object, then you are guaranteeing that the pointed-to object contains all of Derived's data members- but when you point to a Base, then it infact doesn't have that and Bad Things Happen™.
However, Derived is guaranteed to have all of the Base data members in the same locations. That's why a pointer to Base can actually point to Derived.

- 144,682
- 38
- 256
- 465
-
1All derived classes are not "guaranteed to have all of the Base data members in the same locations." – Fred Nurk Feb 08 '11 at 20:07
-
-
@Bo: That will only make things like casting and function calls more complex. Fundamentally, pointer-based inheritance works purely on the basis that when I have a pointer to Base, that the vtable and member variables exist where they would exist in a regular instance of Base. – Puppy Feb 09 '11 at 00:58
Because a derived class includes everything that is in the base class. But a base class does not include everything that is in the derived class.
Type casting a base class to a derived class is not recommended: What happens if you try to access members that are not part of the base class?

- 65,341
- 71
- 269
- 466
This is valid, because a tiger is an animal:
Animal * pAnimal = new Tiger();
This is not valid, because it is not true that the object is a poison dart frog.
PoisonDartFrog * pPoisonDartFrog = new GenericFrog();

- 84,978
- 11
- 107
- 151
-
@DeadMG: You caught me mid-edit. I think an example helps communicate the concept. – Andy Thomas Feb 08 '11 at 19:13
-
1Would today's two downvoters, three years later, care to comment on what they see as flawed in this answer? – Andy Thomas Nov 11 '14 at 20:17
-
...it is not *necessarily* true that the object is a poison dart frog... – Aryaman Jul 19 '18 at 19:33
-
@Aryaman - It is certainly not true, with the reasonable presumption that no one has defined GenericFrog as a subclass of PoisonDartFrog. – Andy Thomas Jul 19 '18 at 20:09
-
-
1@AbhishekMane - It's a generic frog -- a superclass of frogs -- not a particular subclass of frogs such as PoisonDartFrog. – Andy Thomas May 10 '21 at 13:29
The short answer
class A{
public:
method1();
};
class B: public A{
public:
method2();
};
int main(){
// Case 1
A* ptr_base = new B();
// Here I can call all the methods in A by ptr_base even though it is assigned B ...
// ... because B is derived from A and has all the information about methods of A
// Case 2
B* ptr_derived = new A(); // this will cause error
// Now here ptr_derived is assigned information of A ...
// ... So with this information can I call (*ptr_derived).method2(); ?...
// ... the answer is No because A does not have information of method2() ...;
// ... thus this declaration loses its meaning and hence error.
return 0;
}

- 161
- 1
- 1
- 9
class Base
{
public:
int a;
}
class Derived : public Base
{
public:
float b;
}
Base * pBase = new Base();
pBase->a = 7; // setting the value of a in the base
// make a pDerived that points to the SAME DATA as pBase
Derived * pDerived = pBase;
pDerived->a = 5; // this would be okay, base has a public member 'a'
pDerived->b = 0.2f; // error pBase has no data member b and pDerived
// points to the SAME DATA as pBase

- 946
- 12
- 18
Because C++ is a statically typed language, and allowing implicit Base-to-Derived conversions would break the type system. Bjarne Stroustrup did not want any "message not understood" runtime errors.

- 256,549
- 94
- 388
- 662
-
1At the time Bjarne Stroustrup started work on C with classes, C was not even able to type-check a function call :) But yes, C is statically typed, albeit not very strongly. – fredoverflow Feb 08 '11 at 20:17
-
1That's why I don't understand justifying the prevention of the pointer conversion in terms of being statically typed. There are plenty of things that can go wrong at runtime ("message not understood"?), such as dereferencing a null pointer, and Stroustrup's goals appear to lie in the opposite direction of trusting the programmer at runtime. – Fred Nurk Feb 08 '11 at 20:24
-
1@Fred: Maybe you have never been exposed to a dynamically typed language, I don't know. If C++ weren't statically typed, you could just say `p->any_method_name(42, "hello", test);`, and the compiler would not do any checking at compile-time if there is such a method that accepts three parameters, because he would not know that p points to an instance of a class of a statically known type. The checking would be deferred to runtime, which is more expensive and obviously less reliable (but on the plus side, more flexible -- you don't need subtyping or generics, for example). – fredoverflow Feb 08 '11 at 20:32
-
-
@fredoverflow but why there is necessary of this __explicit__ `base to derived conversion` and __implicit__ `derived to base conversion` ? – Abhishek Mane May 10 '21 at 11:32
-
@fredoverflow __2.__ and after doing __explicit__ `base to derived conversion` if I try to access derived class data through this `ptr` it gives random output, sometime it cause runtime errors, is it all part of __Undefined Behavior__ right ? – Abhishek Mane May 10 '21 at 11:56
-
1@AbhishekMane Because upcasts always work (every dog is an animal), but downcasts can fail (not every animal is a dog). If you upcast a dog to an animal and then downcast it to a cat via `static_cast`, undefined behavior ensues. If you downcast via `dynamic_cast`, you get a `nullptr`. – fredoverflow May 12 '21 at 09:37
-
@fredoverflow I think you misunderstood my first Question, I am asking is why it is necessary of such `base to derived conversion` and `derived to base conversion` . is it not better that `base type object` should be store only in `base type ptr` and also `derived type object` should be store only in `derived type ptr` – Abhishek Mane May 13 '21 at 05:37
-
@fredoverflow Now in context of 2nd question what you explained, I am not able to understand it, can you please put some extra light on it. I think my 2nd question is clear to understand – Abhishek Mane May 13 '21 at 05:42
-
1@AbhishekMane A popular example is a `vector
>` containing pointers to cats and pointers to dogs. – fredoverflow May 14 '21 at 16:33 -
@fredoverflow I got it. please answer my 2nd question. after doing __explicit__ `base to derived conversion` if I try to access derived class data through this ptr it gives random output, sometime it cause runtime errors, is it all part of `Undefined Behavior` right ? – Abhishek Mane May 14 '21 at 16:37
-
1@AbhishekMane Casting cat -> animal -> dog will lead to undefined behavior, yes. – fredoverflow May 14 '21 at 22:08
This is because, "the type of a pointer is the type of object the pointer points to". So,
- If we have base type pointer (*B):
then we expect a base type object (and would like to access its functionalities) at the address pointed by B, and if we get a derived type object at that address then also we are able to access the required functionalities. This is because derived type is-a base type.
- If we have derived type pointer (*D):
then we expect a derived type object at the address pointed by D and if we get base type object there then we will not be able to access derived class info from the base type object since base type is-not-a derived type.

- 105
- 1
- 2
- 10
Actions speak more than words. Child too can have Parent Class object. if you understand pointers well, limitations are off to you In below code have printed both values by child class pointer ( which was having Parent class object). Also proved that by printing their address. Any suggestions are welcome!
#include<iostream>
using namespace std;
class Baap{
public:
int a;
void hoo(){ cout<<"hoo\n"; cout<<a;}
};
class Beta:public Baap{
public:
int a;
int b;
void hee(){ cout<<"hee\n"; }
};
int main(){
Baap baap;
baap.a=1;
Beta *beta=(Beta*)&baap;
baap.a=3;
beta->hee();
beta->hoo();
cout<<"\n beta = "<<beta<<"\n&baap = "<<&baap;
return 0;
}
//output
hee
hoo
3
beta = 0x7ffd11dd3834
&baap = 0x7ffd11dd3834

- 11
- 4
-
question is why we __need to typecast__ it by `(beta*)` while passing `address of base class object` to `derived class ptr`, on contrary `passing address of derived class object` to the `base class ptr` we do __not need typecasting__ ( though we can use it that's another part) – Abhishek Mane May 10 '21 at 11:17
-
-
for your question for cast. only a reminder of a basic concept would answer your question. " parent is always memory initialized before than it's child. so if you are trying to have base object in child pointer. then you are trying to violate that you telling the compiler that you should know the size of the object prior to Base class object. So compiler doesn't allow it. As any body can violate and make compiler undecidable in case of runtime allocation using new operator. just try and verify – Vinod Singh May 29 '21 at 08:10
Because a base class pointer can point to an instance of the base class or any derived type. A derived pointer can only point to that derived type or any subclass of it.
struct Base {};
struct Derived : Base {};
struct Derived2 : Base {};
Base* p = new Derived(); //Fine, Derived inherits from Base
Derived* d = new Base(); //Not fine, Base is not an instance of nor derived from Derived.
Derived* d2 = new Derived2(); // Also not fine, Derived2 derives from Base, but is not related to Derived.
As far as the why goes: In general the base pointer is more general than the derived pointer. As such it knows less about the inherited type. A derived pointer cannot be assigned a pointer to a base type without casting simply because it cannot tell if the base pointer is of the Derived type or one of its children.

- 817
- 6
- 6
-
The example was there to help communicate why, and furthermore if you had bothered to read the comments you would notice that it does say WHY. Added some clarification after the point to help. – Washu Feb 08 '11 at 19:15
-
2@AndyThomas-Cramer: Trading upvotes with another user is against the spirit of the system and I'm shocked to see a 4k rep user so blatantly advocating such abuse. – Fred Nurk Feb 08 '11 at 19:49
-
@Fred Nurk - It was not my intent to suggest a quid pro quo. My upvote was unconditional. – Andy Thomas Feb 08 '11 at 20:19
If assign an address from a base class pointer into a derived class pointer, you can potentially assign a base class object to a derived class pointer. You run the risk of accessing derived class members when you don't have a derived class. Whereas derived class methods would work on a base class, they would only do so if the method didn't access derived class member data.
That's a huge risk.
So we force you to cast so that you have to acknowledge the disclaimer that says (you may make a stupid mistake, please be careful).

- 5,162
- 30
- 54
-
"If assign an address from a `base class pointer` into a derived class pointer" I think it should address of a `base class object` into a derived class pointer – Abhishek Mane May 10 '21 at 10:57
In general , a pointer of one type cannot point to an object of a different type. However, there is an important exception to this rule that relates only to derived classes.
In this situation a pointer of type BASE*
may point to an object of type Derived
, i.e a base class pointer can point to a derived class object but vice versa is not true as the base object is not it's sub class object.

- 8,558
- 4
- 35
- 43