0

I am trying to make something that is probably impossible to do with operator overloading. I am particularly interested in overloading assignment operator, which would receive another data type value as its right hand value. It should look like this:

MyClass myclass = "hello world";    <--- Wrong?

MyClass myclass2;
Myclass myclass = myclass2;         <--- Right?

Then MyClass object should receive the string and handle it. Unfortunately, from what I read it is only possible to assign the same data type value to a custom made class. Is that true or was I mistaken?

This is the code I currently have:

class MyClass {
public:
    MyClass() {};
    virtual ~MyClass();
    MyClass& operator = (const MyClass&);
private:
    char* string;
};

MyClass& MyClass::operator= (const MyClass& inc){
    string = inc;
}

int main(int argc, char** argv) {
    MyClass myclass = "hello world";
    std::cout << myclass;
}

As you can see, I want also to cout the object as a string. Basically, I want my custom class to be treated as a string. My search in Google and StackOverflow search engines denied my wish, but is it actually like that or is there a workaround?

Looking forward to hear from you and thank you very much for help in advance!


EDIT: Rollie fixed the main problem. However, how would we cout the string value of the custom object MyClass? Is that even possible, since object output is just the memory address of the object being outputted?

Jonas Hoffmann
  • 315
  • 7
  • 19

1 Answers1

3

MyClass myclass = "hello world"; is not an assignment - it's a constructor, and is logically equivilent to MyClass myclass("hello world");. Overload both the constructor and assignment operators, and you'll have the behavior you are looking for!

Also some comments:

1) It isn't a great idea to name your member variable string - this is the name of a very common STL type

2) setting this variable directly is a time bomb; you aren't copying the value of the string, you are just copying the pointer. switch to std::string so the copies happen automatically

3) to get cout to work properly, see the answer at stackoverflow.com/questions/5508857/how-does-cout-actually-work

Rollie
  • 4,391
  • 3
  • 33
  • 55