Search code examples
c++constructorcopy-constructorassignment-operator

Implicity constructor call


SLet's take this class:

class standardClass
{
    public:
        standardClass(int) {}

        ~standardClass() {}

        standardClass(standardClass&)  {}

        standardClass & operator=(standardClass&)
        {
            return *this; 
        } 
};

int main()
{
    standardClass stdClassObj1(1);
    standardClass stdClassObj2(stdClassObj1);
    standardClass stdClassObj3 = stdClassObj2;
    stdClassObj1 = stdClassObj2;
    stdClassObj2 = standardClass(4);
    stdClassObj2 = 4;
}

I am getting an error on the last assignment.

All these lines are allowed except the last one. In the last one the integer 4 does not invoke the constructor. The error says there is no assignment operator for this. I understand that. But what I'm confused is why this implicit conversion works for a new object (line 1) and not to an existing object (line 2).

I do understand that in the case of line 1, copy constructor is called to create the new AObj4. But in line 2 it invokes the assingment operator. Why cant it make a temporary object with integer 4 and invoke the assignment operator as it would do for line 3?


Solution

  • standardClass(standardClass &objToCopy) // copy constructor
    

    A copy constructor should take a const-qualified reference, like so:

    standardClass(const standardClass &objToCopy)
    

    Same for your assignment operator: that should be

    standardClass & operator=(const standardClass &objToCopy)
    

    Non-const-qualified lvalue references cannot be used with temporary objects, such as the temporary object that would otherwise be created from your literal 4.