1

I have searched the internet and SO for couple of hours on this question. There are similar questions but I could not find an answer to mine. Basically I am trying to pass a rhs object as a parameter of the constructor of another class. I did not receive any errors but neither of the two class's constructors are triggered. If I break the process into two steps: creating one object first and then pass it to the other as lhs, then it works. I tried to have a copy constructor with class2 below and it dose not work either.

Below is the coding. The program runs without errors, but the console records no output.

struct class1
{
    class1()
    {
        std::cout << "class1 constructed" << std::endl;
    }
};


struct class2
{
    class2()
    {
        std::cout << "class2 default constructed" << std::endl;
    }
    template <typename T>
    class2(T)
    {
        std::cout << "class2 with template constructed" << std::endl;
    }

};

int main()
{
     class2 test(class1()); 
     return 0;
}
DavidY
  • 357
  • 5
  • 15

2 Answers2

1
class2 test(class1()); 

In this line Parentheses were disambiguated as a function declaration

Hariom Singh
  • 3,512
  • 6
  • 28
  • 52
1

This is a most vexing parse issue.

class2 test(class1()); is not a variable definition (as you might expect), but a function declaration, the function is named test and returns class2, takes one unnamed parameter which is a pointer to function (which takes nothing and returns class1).

You can use braces instead (since C++11). e.g.

class2 test(class1{}); 
songyuanyao
  • 169,198
  • 16
  • 310
  • 405