Reputation: 559
I am poking around overloaded operators.
For some reason I don't get cout output from within my overloaded function.
class MyString {
public:
MyString(const char aString[20]){
// copy the input string to "data"
for(int i = 0; i < 20; i++){
data[i] = aString[i];
}
}
public:
MyString operator=(const MyString copyFrom){
MyString copyTo("");
cout << "hi";
for(int i = 0; i < 20; i++){
copyTo.data[i] = copyFrom.data[i];
}
return copyTo;
}
public:
char data[20]; // a pointer to memory
};
int main() {
MyString a("hello");
MyString b = a;
cout << b.data << endl;
return 0;
}
When I run my code, I get the following result:
C:\MinGW\bin>g++ stringoverloading3.cpp
C:\MinGW\bin>a.exe hello
C:\MinGW\bin>
Is there something about overloading that kills cout?
Upvotes: 0
Views: 180
Reputation: 206627
The line
MyString b = a;
is not an assignment. It is initialization. The copy constructor is called to initialize the object. To invoke the assignment operator, use:
MyString b;
b = a;
In order to be able to use that, the default constructor has to be implemented first.
Upvotes: 2