Inherited C ++ template constructor

From what I understand about inheritance in C ++, is that whenever a constructor of a child class is called, the constructor of the parent class is called automatically. As for the template constructors, the data type of the template argument is displayed automatically, that is, we do not need to specify the template arguments separately. The program generates a compilation error, which I do not seem to understand.

#include <iostream> #include <list> #include <algorithm> using namespace std; class A{ public: int x; int y; int first(){ return x; } int second(){ return y; } }; class C{ public: float a,b; C(){ a = 0.0f; b = 0.0f; } template<class T> C(T t){ a = t.first(); b = t.second(); } }; class D: public C{ public: float area(){ return a*b; } } int main(){ A a; ax = 6; ay = 8; C c(a); D d(a); cout<<ca<<" "<<cb<<" "<<d.area()<<endl; } 

Compilation error generated

 test.cpp: In function 'int main()': test.cpp:56:8: error: no matching function for call to 'D::D(A&)' test.cpp:56:8: note: candidates are: test.cpp:44:7: note: D::D() test.cpp:44:7: note: candidate expects 0 arguments, 1 provided test.cpp:44:7: note: D::D(const D&) test.cpp:44:7: note: no known conversion for argument 1 from 'A' to 'const D&' 

I have no idea what is going on here. Any ideas?

+4
source share
2 answers

D should pass the constructor argument to C , since you are not using default constructors.

 class D : public C { public: template <typename T> D (T t) : C(t) {} float area () { /* ... */ } }; 

The reason for the error is that you are trying to build D with a parameter, but you did not specify any constructor that would allow you to do this. In addition, you must pass the parameter to C , otherwise the compiler will use the default C constructor.

The compiler error message can be analyzed as follows.

 test.cpp:56:8: error: no matching function for call to 'D::D(A&)' 

The compiler complains:

 D d(a); 

And that he cannot understand how to construct D when transferring something like A

He then presents two options for the constructors that he knows about:

 test.cpp:44:7: note: D::D() test.cpp:44:7: note: D::D(const D&) 

And he points out that for everyone there is a reason why he cannot use it. For the first, he does not accept any arguments. For the second, he cannot convert something of type A to type D

+5
source

From what I understand about inheritance in C ++, is that whenever a constructor of a child class is called, the constructor of the parent class is called automatically.

Caution: the constructor of the parent class is automatically called with the same arguments as the constructor of the child class.

As for the specific problem: there is no constructor declared for class D. You will get a default constructor and copy constructor as freebies, but not this constructor based on templates in class C. Constructors are not inherited.

+1
source

All Articles