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!
To understand the type system of C++, its important to understand the difference between static types and dynamic types. In your example, you defined the types Base and Derived and the variable
ptrwhich has a static type of Base *.Now when you call
new Derived(), you get back a pointer with a static and dynamic type of Derived *. Since Derived is a subtype of Base this can be implicitly converted to a static type of Base * and assigned toptras the static types now match. The dynamic type remains Derived * however, which is very important if you call any virtual function of Base viaptr, as calling virtual functions is always based on the dynamic type of the object, not the static type.