Uhhhh looks like you still don't really understand pointers at all. May not be a good idea to dive into OOP before you do, at least in C++.
persPtr[j]=&gradStudent(name,topic)
This will create a gradStudent object, retrieve it's memory address, then assign the memory address to persPtr[j], and then right away destroy the newly created gradStudent object, which makes the memory your pointer points to invalid. It's a bit hard for me to explain it, I am no teacher, but I'll try.
how can it use new for gradstudent in main,although the size of the object is not known |
The size is known. The size of a char* is fixed (32 bits on most systems), I told you earlier- a pointer is just a number, and a number always has the same size.
Again,BUT what about the delete in main?What does it deallocate? |
delete in main calls the destructors of the gradStudent objects, and then deallocates the memory occupied by them.
I thought that, since object constructor allocate memory for their data,there is no need for main to use new for persPtr[] elements.I saw its not so,can you explain why? |
I don't know how I can this best accross to you, but well... I'll just say this and hope you'll understand. Constructors do not allocate any memory (well, sometimes you
do allocate memory
inside of constructors, but they do not allocate any memory for the objects themselves). Their only purpose is to initialize the objects so they have a valid state after they are created. If you have something like this:
No memory needs to be allocated, because gradStudent is created in memory that already belongs to the program. Only with
new
(and
malloc
in C you actually allocate new memory on runtime.