code error

Hi,

Why this code does not work?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Name {
	char *mp;
	int mlen;
public:
	Name(const char *pname) : mlen(strlen(pname)), mp(new char[mlen + 1]) 
	{
		strcpy(mp, pname);
	} 
	void display()const 
	{
		cout << mp << endl;
	}
};


int main()
{
	Name name("Firix bills");

	name.display();

	return 0;
}

1
2
3
4
5
6
7
8
class Name {
	char *mp;  // since mp is declared first in the class, it in initialized first
	int mlen;  // mlen is initialized after mp
public:
   // the order you put them in here doesn't matter:
	Name(const char *pname) : mlen(strlen(pname)), mp(new char[mlen + 1])

   // therefore, you are using mlen before it was initilized. 


To correct this, declare mlen before mp, or allocate mp in the body of the ctor.


Also, don't forget to delete[] mp in your dtor and write a proper copy ctor and assignment operator.
Because mlen gets initialized after mp
The order of initialization of class members depends on the order of their declarations
Your compiler should give a warning on the code above

[edit] slow connection...
Last edited on
ok.
Topic archived. No new replies allowed.