0

I have 2 test classes:

class B {
    public:
    B(int i) {
       qDebug() << "B constructor ";
    } 
};

class A {
    public:
    A(B b) {
        qDebug() << "A constructor ";
    } 
};

Now i want to create A object with B, thats what i do:

int i = 5;
A test (B(i)); //does not work

Code compiles without errors, but second line doesnt execute at all. I've made some tests, and code below works well:

int i = 5;
A test (B((int)i)); //works

A test (B(5)); //works

So, i guess compiler cant interpret 'i' as int inside B constructor call, but why?

M. Paul
  • 53
  • 4

1 Answers1

0

This:

A test(B(i));

is the same as the:

A test(B i);

which is a function declaration, not a call to constructor due to a most vexing parse. There is a rule that states (S. Meyers, "Effective Modern C++"):

anything that can be parsed as a declaration must be interpreted as one

To avoid that use braced initialization (instead of parentheses ()) as functions can't be declared with {} braces:

A test{B(i)};

That being said there are no "nested constructors calls" in your example.

Ron
  • 14,674
  • 4
  • 34
  • 47