Anand
Anand

Reputation: 73

explicitly using constructor call in main as a function call parameter

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

Upvotes: 2

Views: 941

Answers (2)

Prasoon Saurav
Prasoon Saurav

Reputation: 92854

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.

Upvotes: 7

Oswald
Oswald

Reputation: 31647

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

Upvotes: 1

Related Questions