4
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 that due to the compiler optimization (copy elision) as discussed in this link?

But if I have a B class constructor and re-write the code like 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()
}
Community
  • 1
  • 1
Ibrahim Quraish
  • 3,889
  • 2
  • 31
  • 39

3 Answers3

3

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 are facing it called most vexing parse, and it means compiler is not able to decide whether you want a function declaration or variable definition.

[edit]

I should also add that standard requires compiler in such case to choose function declaration.

[edit]

clang is actually more helpfull in this case, and gives hint to use partentheses:

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 warning generated.

marcinj
  • 48,511
  • 9
  • 79
  • 100
1
B b(A());

Is ambiguous and may be interpreted either as a variable declaration or as a declaration of a function that returns a restult of type B and takes a single unnamed parameter of type a function with no parameters and returns a result of type A. Although you may think first one should take place the standard dictates in fact the second one will happen. See the article about most vexing parse in wikipedia.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

Instead of creating A object after B object creation, create first As object in main.

A a;
B  b(a); 
user3273866
  • 594
  • 4
  • 8