user1232138
user1232138

Reputation: 5541

Assign const ref to non-const object

In the following code we are returning a const object and collecting it in a non const object, and still it compiles without an error or a warning..

class foo
{
    int i;
public:
    const foo& call() const
    {
        return *this;
    }
};

int main()
{
    foo aa, bb;
    bb = aa.call();
}

Upvotes: 0

Views: 1263

Answers (2)

uwedolinsky
uwedolinsky

Reputation: 611

This code calls the implicitly defined copy assign operator foo& foo::operator=(const foo&):

    int main()
    {
        foo aa, bb;
        bb = aa.call();//  equivalent to bb.operator=(aa.call());
    }

The argument to that assign operator is a const reference to foo, so can bind directly the reference returned by foo::call. There is no copy constructor called in any of this code.

Upvotes: 0

Nick
Nick

Reputation: 25799

You're actually taking a copy of a const object when you do bb = aa.call( ) which will call the implicit copy constructor on foo.

If you wanted to break the compilation then try:

foo aa;
foo& bb = aa.call( );

Note:

The implicit copy constructor is generally defined as:

foo( const foo& exist );

and in the default case just does a member-wise copy.

Upvotes: 14

Related Questions