Why doesn't my assignment operator overload work properly?

I am trying to create a String class like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class String{public:
	string s;

	String& operator=(String a){
		s = a.s;
		return *this;}
	String& operator=(string a){
		s = a;
		return *this;}
	String& operator=(char* a){
		s = a;
		return *this;}
}

int main(){
	String k;
	k.s = "I AM K";

	String n1 = k;
	String n2 = "dasdasdad";
}


For n1 it compiles, for n2 not.
How can I fix this?
Thanks
Last edited on
What's the error message?
Hi Dave,

I am not sure your problem is with your class code. It appears your problem is with your client code in main. You are using the assignment operator on objects that have not been instantiated yet. In the first instance on line 19 you are not actually calling your overloaded assignment operator for String n1. You are calling the implicit copy constructor of the class String. The compiler creates the implicit copy constructor when none has been explicitly defined. The implicit copy constructor performs a member-wise copy of the data members of k to n2. In the second case String n2 the compiler is not using your overloaded assignment operator for a string it is actually looking for a overloaded class constructor of the form String(string s). It will not use the overloaded assignment operator to instantiate a member of the class.

In short, it is not that one of your overloaded assignment operators works and the other does not. The problem is that they are never actually used in the client code.

@JayBari thanks, I didn't know copy constructors function like that. I changed it and now it works!
Topic archived. No new replies allowed.