pointer question

Hi all,
Currently Im studying virtual funcs& polymorphism but I recognized that I have problem with basics of pointers (as many beginners,I think).

When I say;
Base* ptr=new Derived; // Derived is a class derived from Base

I'm defining a derived class object (without a name?),allocating memory and assigning its address to ptr.Right?

But when I say
delete ptr
I deallocate pre-allocated memory for object of class Derived.What about ptr?Is it also deleted,cleared or sth?

Besides,when I use this
1
2
3
Base x; //define object,not pointer
//delete x; not a pointer
delete &x; //this works,it invokes the destructor of the base class. 


Can you also explain this?What is deleted in last expression?Do we still have a pointer(or adress) value remaining after that expression?

You see I'm confused with basics.I need your clear explanations.


Last edited on

What about ptr?Is it also deleted,cleared or sth?


A pointer is just a number that your program uses to store memory locations.
Base* ptr=new Derived;
This creates a new Derived object in the memory, and stores the memory address of that object in ptr.
delete ptr;
destroys the object pointed to by ptr.

Here, nothing happens with ptr itself. It will still hold the same number pointing to the same memory region. Just that that memory region does no longer belong to your program.
Last edited on
This code is plain wrong though and is undefined behaviour.

1
2
3
Base x; //define object,not pointer
delete &x; //
Last edited on
Oh yeah, I missed that one. You only call delete on dynamically allocated objects.
1
2
3
4
This code is plain wrong though and is undefined behaviour.

Base x; //define object,not pointer
delete &x; // 

I expected an error from the compiler for it,but it compiled.Im also surprised it invoked destructor of the base class.I didnt know that its wrong.
Well, there is no compilation error because it's not syntactically wrong. But if you do this, all sorts of nasty things can happen. It's a bit like playing russian roulette, sure you might get away with it sometimes, but that doesn't make it less dangerous.
Well, there is no compilation error because it's not syntactically wrong. But if you do this, all sorts of nasty things can happen. It's a bit like playing russian roulette, sure you might get away with it sometimes, but that doesn't make it less dangerous.

Thanks, I got it.It may cause undesired results.

I have another question related to pointer and dont want to start a new topic.The question will follow the code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class person // person class
{
protected:
char* nameptr;
public:
person(char* np) // 1-arg constructor
{
int length = strlen(np); /
nameptr = new char[length+1]; 
strcpy(nameptr, np); 
}
virtual ~person() = 0 // destructor
{
cout << "nperson Destructor";
if(nameptr != NULL) // if it has been used,
        delete[] nameptr; // delete name
}
virtual void putData()
{ cout << "nName = " << nameptr; }
};

class gradStudent : public person // gradStudent class
{
private:
char* topicptr; // ptr to thesis topic
public:
gradStudent(char* n, char* t) : // 2-arg constructor
person(n), topicptr(NULL)
{
int length = strlen(t); 
topicptr = new char[length+1]; 
strcpy(topicptr, t);
}
~gradStudent() // destructor
{
cout << "n GradStudent destructor";
if(topicptr != NULL) // if it has it been used,
   delete[] topicptr; // delete thesis topic
}
virtual void putData()
{
person::putData();
cout << "n Thesis topic = " << topicptr;
}
}; // end gradStudent class

int main()
{
int j;
const int total = 3;
person* persPtr[3]; // list of pointers to persons
char name[40]; // temporary storage
char topic[80];
for(j=0; j<total; j++) // get data, make gradStudents
{
cout << "nEnter name:";
cin >> name;
cout << " Enter thesis topic: ";
cin >> topic;
persPtr[j] = new gradStudent(name, topic);
}
for(j=0; j<total; j++) // display gradStudents
persPtr[j]->putData();
for(j=0; j<total; j++) // delete gradStudents
delete persPtr[j];
return 0;
} // end main() 


Here,we have an array of pointers.Program allocates memory using new in main for gradstudent class.Gradstudent objects have two char pointers (1 in derived class,1 in base class).I can understand that in constructors it allocates memory for name and thesis topic,since they are not array..BUT,how can it use new for gradstudent in main,although the size of the object is not known?This is something like "pointer to object which contains pointers" to me.Also,I can understand that delete s in destructors delete memory allocated for name and thesis strings.Again,BUT what about the delete in main?What does it deallocate?

I know this is a somewhat long question but it will help me get rid of confusion on pointers.
Last edited on
I tried persPtr[j]=&gradStudent(name,topic),instead of line 60.As a result I obtained garbage values,strange output.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?
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:
 
gradStudent a;

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.
Last edited on
@hanst99;
First of all thanks for reading my rather long post and your long,explanatory answer.
Maybe you are right about not to dive into OOP,but when I studied pointers chapter I felt I understood it to some degree.Then I studied Inheritance and now Polymorphism.Pointers come accross to me everytime with a different problem.

Anyway,I think I understood your answer,gradstudent has a known size,it hold two pointers of type char,whatever text we put in those adresses,the size of the object is fixed.(?)Since we allocate text with constructor,we deallocate it using destructor.Then,in main we deallocate memory allocated for the object.

I saw such an initialization in a previous chapter,I think that made me confuse,
1
2
3
shape* sharray[3] = { &bowl(10, 0, 3), // initialize array,here shape is base class
                             &square(20, 1, 5),  //and bow,square,cap are derived classes
                              &cap(30, 1, 7) };// 3 integer data is kept in base class 

so that I thought I could use
persPtr[j]=&gradStudent(name,topic).
Topic archived. No new replies allowed.