Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Assignment Operators

I made the following operator overloading test:

#include <iostream>
#include <string>

using namespace std;

class TestClass
{
    string ClassName;

    public:

    TestClass(string Name)
    {
        ClassName = Name;
        cout << ClassName << " constructed." << endl;
    }

    ~TestClass()
    {
        cout << ClassName << " destructed." << endl;
    }

    void operator=(TestClass Other)
    {
        cout << ClassName << " in operator=" << endl;
        cout << "The address of the other class is " << &Other << "." << endl;
    }
};

int main()
{
    TestClass FirstInstance("FirstInstance");
    TestClass SecondInstance("SecondInstance");

    FirstInstance = SecondInstance;
    SecondInstance = FirstInstance;

    return 0;
}

The assignment operator behaves as-expected, outputting the address of the other instance.

Now, how would I actually assign something from the other instance? For example, something like this:

void operator=(TestClass Other)
{
    ClassName = Other.ClassName;
}
like image 727
Maxpm Avatar asked Aug 28 '26 08:08

Maxpm


1 Answers

The code you've shown would do it. No one would consider it to be a particularly good implementation, though.

This conforms to what is expected of an assignment operator:

TestClass& operator=(TestClass other)
{
    using std::swap;
    swap(ClassName, other.ClassName);
    // repeat for other member variables;
    return *this;
}

BTW, you talk about "other class", but you have only one class, and multiple instances of that class.

like image 65
Ben Voigt Avatar answered Aug 29 '26 21:08

Ben Voigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!