Template class: no default constructor

I know there are a million posts about this, but I still can’t understand why this is not working = /

this line:

test = new Test2<Test>;

gives me this error:

error C2512: 'Test2<PARENT>' : no appropriate default constructor available
with
[
    PARENT=Test
]

the code:

template<class PARENT>
class Test2;

////////////////////////////

class Test
{
public:
    Test2<Test> *test;

    Test()
    {
        test = new Test2<Test>;
    }
};

/////////////////////////////

template<class PARENT>
class Test2
{
public:
    PARENT *parent;
};

////////////////////////////

can someone help me?

+3
source share
3 answers

At the time of instantiation (i.e., inside the constructor Test), the entire compiler is still a direct declaration Test2<>; he does not yet know which constructors are available.

To solve, move the definition Test2<>before Test, or move the constructor Testdefinition outside the class definition (and after the definition Test2<>).

+6

For me, your code gives (correctly, IMHO) an error:

invalid use of incomplete type 'struct Test2<Test>'

g++ 4.5.1. , :

test = new Test2<Test>;

Test2 , .

0

The string test = new Test2<Test>;executes the internal default constructor of Test. And this line will call the default constructor / constructor with no arguments. The Test constructor is not yet completed when the statement is called.

-1
source

All Articles