Difference

Hi! I'm new here... And i'm new in cpp programming!

I'm sure you can help me here..
I do not understand the difference...

1
2
3
4
  ClassName::ClassName(string var1, string var2){
	variable1 = var1;
        variable2 = var2;
}


And:

 
ClassName::ClassName(string var1, string var2) : variable1(var1), variable2(var2){}


Why it still works? It's the same thing?
Thank you
The difference is when the objects are constructed.


1
2
3
4
  ClassName::ClassName(string var1, string var2){
	variable1 = var1;
        variable2 = var2;
}


Here... ClassName's 'variable1' and 'variable2' objects will be default constructed, then reassigned.

Whereas here:
 
ClassName::ClassName(string var1, string var2) : variable1(var1), variable2(var2){}


variable1 and variable2 will not be default constructed, but instead will be copy constructed.



It's basically the same idea as this:

1
2
3
4
5
6
7
8
string foo = "example";

string bar(foo);  // copy construct bar

// vs

string bar;  // default construct bar
bar = foo; // then reassign bar 



Directly copy constructing is usually more efficient... and should be preferred. The default constructor for string doesn't now how much space it needs to allocate (if any) so it might allocate a small chunk, only to throw that chunk away immediately after it gets reassigned. Whereas if you copy construct, it immediately knows how big it needs to be in order to hold all the string data because you're giving it the string data up front.


So yeah... prefer this form:

1
2
ClassName::ClassName(string var1, string var2) : variable1(var1), variable2(var2){}
 
Hi!

Great response, thank you very much.

Cheers
Topic archived. No new replies allowed.