-2

Notes: 1) Person is the base class of Student 2) Person contains name as the only data variable 3) Student contains society . The society acts as a pointer to a text string which contains the name of the student's club.

I have difficulty in understanding the fourth line:

int main (){
Person* p1;
p1=new Student("John", "Drama Society");   //This line
delete p1;
}

Isn't p1 a Person pointer pointing to a memory address in the heap? As far as I know, pointer variable is just a 32-bit or 64-bit(system-dependent) location in memory. How can it be initialized just like objects of type Person?

I know my concept is wrong, please help me find them out :(

Yin
  • 3
  • 1
  • Result of new is a pointer. Pointer to person can be initialised with pointer to student. What is your question? – Yunnosch Jul 08 '17 at 15:37

2 Answers2

2

What is happening is that the call to new allocates a Student object on the heap and then returns a pointer to it. Then you assign that pointer to p1. So p1 now points to a Student object on the heap.

The constructor call after new is just how C++ syntax for new works. That constructor will be used to initialize the object on the heap.

Curious
  • 20,870
  • 8
  • 61
  • 146
0

You are asking about polymorphism. You have to distinguish between static and dynamic type. The static type of a pointer is specified at declaration. In this case static type of p1 is Person. The dynamic type can be any descendant of the static type and can be defined at run-time which is Student in your example.

You can find a great explanation here: https://stackoverflow.com/a/7649711/8244162

Jónás Balázs
  • 781
  • 10
  • 24