I just found that I am confused about one basic question in C++
class Base {
};
class Derived : public Base {
}
Base *ptr = new Derived();
What does it mean? ptr is pointing to a Base class or Derived class? At this line, how many memory is allocated for ptr? based on the size of Derived or Base?
What's the difference between this and follows:
Base *ptr = new Base();
Derived *ptr = new Derived();
Is there any case like this?
Derived *ptr = new Base();
Thanks!
For Base *ptr = new Derived();
memory is allocated according to Derived
class. ptr
points to the object but the compiler is instructed to only "grant access" (visibility) to the members of the object that are declared in the Base
class.
Of course the memory associated with the pointer ptr
is the same i.e. independent of the object it is instructed to point to. Usually, the size of a "pointer object" is constant on a CPU architecture e.g. 32bits / 64bits (or smaller on embedded devices for example).
For Derived *ptr = new Base();
: no, this is invalid.
Class Derived
isn't just a class Base
but is defined as deriving from Base
: hence, a pointer instance to a Derived
object instance can't be just assigned to an object instance of class Base
.
You might consider perusing the very good Wikipedia contributions on Polymorphism and Inheritance.
Polymorphism
ptr is a pointer; it has the same size regardless of what it points to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With