Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring pointer to base and derived classes

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!

like image 230
skydoor Avatar asked Nov 28 '22 11:11

skydoor


2 Answers

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.

like image 188
jldupont Avatar answered Dec 10 '22 14:12

jldupont


Polymorphism

ptr is a pointer; it has the same size regardless of what it points to.

like image 29
Ignacio Vazquez-Abrams Avatar answered Dec 10 '22 12:12

Ignacio Vazquez-Abrams