Click here to Skip to main content
15,851,395 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,
Can someone let me know what is the use of explicit copy constructor with relevent examples? Please see the following code along with comments. I am using g++ compiler.

1 #include<iostream>;
2
3 using namespace std;
4
5 class Y {
6 public:
7 Y()
8 {}
9 Y( int x)
10 {}
11 explicit Y(const Y&){}
12
13 };
14
15
16 int main()
17 {
18 Y obj; // works
19 Y obj2 = obj; // doesn't work.
20 return 0;
21 }
22
Posted

explicit means "Only allow objects to be created with an explicit statement that construction is happening." When you write:

A a;
A b = a;

the second line is implicitly a copy construction and the compiler won't let it happen if you've marked the copy constructor explicit. If you write:

A a;
A b( a );

You're explicitly saying "this is a copy construction" and the compiler lets it happen, whatever you've marked the copy constructor (provided it's public).

Cheers,

Ash
 
Share this answer
 
Comments
Yuvaraj Gogoi 1-Jun-10 2:10am    
Thanks for the answer... Its pretty clear now!
The keyword "explicit" before constructor with single argument avoids automatic type conversion.

It may be necesary if you are using classes with many constructor and assignement operator override.

The better example would probably be:

class Y {
 public:
 Y()
 {}
 explicit Y( int x)
 {}
 Y(const Y&){}

};

int _tmain(int argc, _TCHAR* argv[])
{
 Y obj; // works
 Y obj2 = 0; // doesn't work.
 Y obj3 = Y(0); // does work.

	return 0;
}
 
Share this answer
 
Comments
Yuvaraj Gogoi 31-May-10 11:03am    
But my question was on explicit copy constructor not explicit constructor!
Anyway thanks for the answer.
Yuvaraj Gogoi 31-May-10 11:04am    
Reason for my vote of 1
Sry... the answer was not what I expected!
voloda2 31-May-10 11:15am    
Sory.

It is used to prevent copying of objects at function calls or with the copy-initialisation syntax.

Following will not work with your original class.

Y M(void)
{
        Y y;
	return y;
}
Yuvaraj Gogoi 31-May-10 11:42am    
Can I know why if explicit keyword is used and even the copy-initialisation syntax won't work? I have this doubt because copy-initialisation syntax doesn't involve any automatic type casting!
Thanks for your answer again!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900