constructor

Hello folks,

could you please explain me the following code?
 
name_class *name = new name_class()

the constructor is
1
2
3
name_class::name_class()
{
}


I've understood that I define a pointer called name and invoke the constructor that allocate the memory for that pointer. correct? could you tell more?
when I've to call delete?
thanks
Last edited on
for example:


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
class name_class{
char *name;
public:
   name_class(char *n)
   {
        name  = new char[strlen(n) + 1];
		strcpy(name, n);
   }

	~name_class()
	{
		delete [] name;
	}

	void print()const
	{
		cout << "(" << name << ")" << endl;
	}
};

int main()
{
	name_class *name = new name_class("Gabboshow");


	name->print();


	delete name;



	return 0;
}

Gabboshow wrote:
I've understood that I define a pointer called name and invoke the constructor that allocate the memory for that pointer. correct?
wrong. 'new' allocates the memory where 'name_class' will reside then calls the constructor.

Gabboshow wrote:
when I've to call delete?
When you don't need that object anymore. Be careful when you gave away that pointer it's not always trivial. Therefore smart pointer where invented
Topic archived. No new replies allowed.