Why are neither the constructor operator nor the assignment operator executed when declaring an object?

Testing program

#include <iostream>
using namespace std;

class A
   {public:
       A (): I(0) {cout << "default construcot" << endl; };
       explicit A (int i): I(i) {cout << "another construcot" << endl; };
       A (const A& a): I(a.I) {cout << "copy constructor" << endl; }
       A& operator = (const A& a)
          {cout << "assignment operator" << endl; 
           if (this == &a) return *this; 
           I = a.I;
           return *this; 
          }
       void show () {cout << I << endl; };
    private:
       int I;
   };

int main ()
   {A a = A(1);
    A b;
    b = A(2);
    a.show();
    b.show();
    return 0;
   }

conclusion

another construcot
default construcot
another construcot
assignment operator
1
2

shows that the object "a", unlike "b", was built from A (1) "directly" without executing the assignment operator. But the copy constructor was not executed either. What for? Is there any way to force the assignment operator in this case? I would expect this behavior if I wrote

A a (1);

but I want

A a = A(1);

which should be different from the first case. Or not?

(Actually, the problem arises when I have a class B derived from A and require the assignment operator to handle the declaration as A a = B (...).)

+3
5

. , (, , , a).

.

. , ( ). , .

, : A a (1);

, .

B, A, , A a = B (...).)

, B A B. ?

A const& a = B();
+3

A a = A(1);

:

A a;
a = A(1);

= , = . . , , , (RVO, ..).

+6

? , .

? .

+1

, , , . , , , , , .

+1

, A a(1); A a = 1; , .

+1

Source: https://habr.com/ru/post/1782345/


All Articles