The constructor is not called in this aggregation class

class A {
public:
    A() { cout << "A()" << endl; }
};
class B {
public:
    A a;
    B(const A& a1) : a(a1) { cout << "B(const A&)" << endl; }
    /* B(const A& a1) { a = a1; cout << "B(const A&)" << endl; } */
};
int main() {
    B b(A());  /* no ouput */
}

No output is generated for the above code. Is this related to compiler optimization (copy elision) as discussed in this link ?

But if I have a class B constructor and rewrite the code as shown below:

class A {
public:
    A() { cout << "A()" << endl; }
};
class B {
public:
    A a;
    B() {}
    B(const A& a1) : a(a1) { cout << "B(const A&)" << endl; }
    /* B(const A& a1) { a = a1; cout << "B(const A&)" << endl; } */
};
int main() {
    B().a; // gives output A()
}
+4
source share
3 answers

add an extra pair of parentheses:

B b((A())); 

// you can also fix it using new C++11 initialization syntax:
B b{A()};

the problem you encountered caused the most unpleasant parsing, which means that the compiler cannot decide whether you want a function declaration or a variable definition.

[edit]

I should also add that the standard requires the compiler to select a function declaration in this case.

[edit]

clang :

http://rextester.com/PECQ53431

source_file.cpp:16:8: warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
    B b(A());  /* no ouput */
       ^~~~~
source_file.cpp:16:9: note: add a pair of parentheses to declare a variable
    B b(A());  /* no ouput */
        ^
        (  )

1 .

+3
B b(A());

, , restult B A. , , , , . . .

+1

Instead of creating an object A, after you create the object B first create the first object A s.

A a;
B  b(a); 
0
source

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


All Articles