2

I am trying to understand how explicit constructor call in main works using the following code.

#include<iostream>

using namespace std;

class Dependency1
{
      bool init;
public:
  Dependency1() : init(true) {
    std::cout << "Dependency1 construction"
              << std::endl;
  }
  void print() const {
    std::cout << "Dependency1 init: "
              << init << std::endl;
  }



};


class Dependency2 {
   Dependency1 d1;
public:
   Dependency2(const Dependency1& dep1): d1(dep1){
     std::cout << "Dependency2 construction ";
     print();
   }
   void print() const { d1.print(); }
};

void test( const Dependency1& dd1)
{
    cout  << " inside Test \n";
    dd1.print();
}



int main()
{

    test(Dependency1());
    Dependency2 D1(Dependency1()); // this line does not work

    return 0;
}

Function test is being called where constructor Dependency1() is used as a function call instead of Dependency1::Dependency1( ) and the code runs perfectly fine.

Now if I use similar concept to create an object D1 of Dependency2, it does not work. Seems I am doing something wrong here based on wrong understanding.

Need to know how the Compiler resolves Dependency1() call in main even if scope resolution is not used and why it does not work when I use it as a parameter in constructor of Dependency2

Thanks, Anand

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Anand
  • 73
  • 1
  • 5

2 Answers2

7

test(Dependency1())

This calls a function test and passes a temporary object of class Dependency1. Because the formal parameter in the definition of test is a reference to const and because temporaries can be bound to const references your code works.

Dependency2 D1(Dependency1()); // this line does not work

This is called C++ most vexing parse. D1 is interpreted as a function returning Dependency2 and taking an argument a pointer to function returning Dependency1.

Try Dependency2 D1((Dependency1())); and see the change in output.

Note: Putting an extra pair of parenthesis would make the compiler treat (Dependency1()) as an expression.

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
1

Dependency1() creates a temporary object of type Dependency1, that is passed to function test.

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • thanks, But why it does not work when I use similar thing to create Dependency2 object. – Anand Dec 24 '10 at 05:30