CuriousGeorge
CuriousGeorge

Reputation: 7400

Template class: No default constructor

I know there are a million posts about this, but I still can't figure out why this isn't working =/

this line:

test = new Test2<Test>;

gives me this error:

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

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 out?

Upvotes: 3

Views: 2799

Answers (3)

Mayank
Mayank

Reputation: 5738

The line test = new Test2<Test>; is executing inside default constructor of Test. And this line will call the default constructor/constructor with no arguments. The constructor of Test is still not complete when the mentioned statement is being called.

Upvotes: -1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

At the point of instantiation (i.e. inside the Test constructor), all the compiler has so far is a forward declaration of Test2<>; it doesn't yet know what constructors are available.

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

Upvotes: 6

user2100815
user2100815

Reputation:

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

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

This is with g++ 4.5.1. At the point you say:

test = new Test2<Test>;

Test2 has not been defined, only forward declared.

Upvotes: 0

Related Questions