Orokusaki
Orokusaki

Reputation: 43

Trying to assign an object to an object of different type in C++

I'm trying to understand the behaviour of this code:

class A {
public:
    int a;
    A(int x = 0): a(x) {cout << "A-ctor" << endl;}
    ~A() {cout << "A-dtor" << endl;}
};

class B {
public:
    int b;
    B(int x = 0): b(x) {cout << "B-ctor" << endl;}
    ~B() {cout << "B-dtor" << endl;}
};

int main() {
    A a;
    B b;
    a = b.b;
    return 0;
}

The output of this program is:

A-ctor
B-ctor
A-ctor
A-dtor
B-dtor
A-dtor

My question is, in this line in main(): a = b.b, an instance of class A is created and immediately destroyed. Why is this happening? Moreover, shouldn't I get a compilation error when trying to assign an object of one class to a different class?

Upvotes: 3

Views: 58

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122450

This assignment

a = b.b;

works, because there is a user defined (implicit) conversion from int to A via this constructor:

A(int x = 0): a(x) {cout << "A-ctor" << endl;}

Such constructors are called converting constructors (can be called with single argument and is not declared explicit). If you want to prevent the implicit conversion declare it as exlicit.

Output comes from

A a;            // A-ctor
B b;            // B-ctor
a = b.b;        // A-ctor

Note that the last line actually calls the compiler generated A::operator=(const A&), because you did not declare a A::operator=(int). A temporary A is created via the above constructor.

... and then desctructors as usual in reverse order of construction.

Upvotes: 5

thejonny
thejonny

Reputation: 533

The value a can be assigned from an A. b.b can be converted to an A:

b.b is a int, and A has a constructor with an int argument, so it is used as converting constructor. See https://en.cppreference.com/w/cpp/language/converting_constructor

Then, the newly created A is copied to a using it's default operator=, and then the A(b.b) it is destroued as it is not needed anymore.

Upvotes: 2

Related Questions