wrong constructor called

I have the following code in main.cpp:

1
2
3
4
5
  String test ("abc");

  test = "bob";


note: the String (with a capital S) is my own class

at 'test = "bob"' I would expect the following assignment operator function to be called:

1
2
3
4
5
6
String String::operator= (const char* str)
{
	set_str(str);
	
	return *this;	
}


but this constructor seems to be called:

1
2
3
4
5
6
String::String (const String& str)
{
	internal_string = str.internal_string;		//copy existing pointer
	set_str(internal_string);

}


Can anyone help me understand what is going on here?

Thanks!
Well, you're returning a String by value. Are you sure the constructor isn't being called in addition to the operator, rather than instead of?
Ah, yes both are being called.

I was told I needed to return *this in order to enable chaining of the constructors...
Change the return type to String & to avoid the constructor call.
Registered users can post here. Sign in or register to post.