Constructors, Please help with the program

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
#include<iostream>
#include<string>
using namespace std;

class str
{
char *name;
int len;
str()
{
len=0;
name=0;
}
str(const char *s)
{
len=strlen(s);
name=new char[len+1];
strcpy(name,s)
}
void display(void)
{
cout<<name<<endl;
}
};

int main()
{
str s1="New';
str s2("York");
str s3(s2);
s3.display();
return 0;
} 


output:
York

My question is without any copy constructor defined in the class,
how does the following statement works?
str s3(s2);
Here we are passing an object as argument
doesn't that mean we need a copy constructor(Call by ref)

str(str &s)
{
len=strlen(s);
name=new char[len+1];
strcpy(name,s.name);
}

And
Please Help
Last edited on
A copy constructor will be created automatically if you don't declare one. It will just copy each member to the new object so s3.name and s2.name will both point to the same data. Probably not what you want.
@Peter87 Thanks for the help,
btw is there a difference between

str s2("York");

and

str s1="New";

Yes and no.

str s1="New"; is equivalent to str s1(str("New")); but the compiler is allowed to optimize away the extra constructor call resulting in the same machine code as str s2("York");.

If you delete the copy constructor or make it private str s1="New"; will fail to compile while str s2("York"); still compiles.
Last edited on
Hey i am a lil confused here, how is compiling of

str s1="New";

related to the copy constructor?

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
#include<iostream>
#include<string>
using namespace std;

class str
{
char *name;
int len;
str(str &s)
{
len=strlen(s);
name=new char[len+1];
strcpy(name,s.name);
}


public:
str()
{
len=0;
name=0;
}
str(const char *s)
{
len=strlen(s);
name=new char[len+1];
strcpy(name,s)
}
void display(void)
{
cout<<name<<endl;
}
};

int main()
{
str s1="New';
s1.display();
return 0;
}  


Here in the above code, i have made copy constructor as private and still New is printed

str s2("York"); is direct initialization: http://en.cppreference.com/w/cpp/language/direct_initialization

str s1="New"; is copy initialization: http://en.cppreference.com/w/cpp/language/copy_initialization

Actually, your example doesn't compile, exactly because the copy constructor is not accessible: http://liveworkspace.org/code/3546967c9c5e61813f3fb72773456a11
Last edited on
Topic archived. No new replies allowed.