Andy
Andy

Reputation: 366

Do templates need overloaded constructors?

I just finished watching some videos of template and I think I am missing some concepts. Why doesn't the constructor get called, or why the object is not created when the constructor is not overloaded with a desired data-type? Since I am writing the <int> doesn't the compiler know I am going to be dealing with an int?

template <class T>
class Generic {
    T var;
public:
    Generic(){cout << "ctor called " << endl;}
    //Generic (T v) {var = v;}
};


int main () {

    Generic<int> generic1();

}

Can't I create an object like this and then modify the value of T var through a setter? Why should I need an overloaded constructor e.g. Generic<int> generic1(9); ?

Upvotes: 2

Views: 146

Answers (1)

songyuanyao
songyuanyao

Reputation: 172964

This is a Most vexing parse issue.

Of course you can initialize the object via the default constructor, and modify the value via a setter later, the problem here is that you're not defining a variable. Generic<int> generic1(); is a declaration of function, which is named generic1, takes no arguments and returns Generic<int>.

What you want is

Generic<int> generic1;

or

Generic<int> generic1{}; // since C++11

Upvotes: 7

Related Questions