2

In the following, shouldn't base class constructor be generated by the compiler based on derived class constructor argument type?

template <class T> class foo { int a; public: foo(T a){} // When I convert the constructor to a function template, it works fine. // template <typename T> foo(T a){} }; class bar : public foo<class T> { public: bar(int a):foo(a){} }; int main(void) { bar obj(10); system("pause"); return 0; } 

error C2664: 'foo::foo(T)' : cannot convert parameter 1 from 'int' to 'T'

I understand the error, but why is that ?

1 Answer 1

5

The syntax in class bar : public foo<class T> is incorrect.

  • Either bar depends on a template parameter T and bar should be a template :

    template<class T> class bar : public foo<T> { public: bar(int a):foo(a){} }; int main() { bar<int> obj(10); } 
  • Or you want bar to inherit from a specific instantiation of foo such as :

    class bar : public foo<int> { public: bar(int a):foo(a){} }; int main() { bar obj(10); } 
Sign up to request clarification or add additional context in comments.

2 Comments

From the first code, T in foo<T> say that bar template parameter is also a foo template parameter. Am I correct ?
@Mahesh yes, bar<int> inherits from foo<int>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.