Inheritance and patterns and virtual functions (this can become messy)

Just find your way around the templates, so I tried a few things.

Let me know what I'm doing wrong here.

I am trying to overload the virtual method of inherited patterns.

// class templates #include <iostream> using namespace std; template <class T, class A> class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} virtual A getmax (); }; template <class T, class A> A mypair< T, A>::getmax () { A retval; retval = a>b? a : b; return retval; } template <class T, class A> class next : public mypair <T, A> { A getmax () { cout <<" WHOO HOO"; } }; int main () { mypair <double,float> myobject(100.25, 75.77); next<double,float> newobject(100.25, 75.77); cout << myobject.getmax(); return 0; } 

`

This gives an error:

 function.cpp: In function 'int main()': function.cpp:35: error: no matching function for call to 'next<double, float>::next(double, double)' function.cpp:25: note: candidates are: next<double, float>::next() function.cpp:25: note: next<double, float>::next(const next<double, float>&) 

If this is not the right way, then some template inheritance information will be great

+4
source share
2 answers

The next class does not automatically inherit constructors from its parent class. You must explicitly define any constructors. This applies to all derived classes, regardless of whether templates and virtual functions are involved.

If you want to define a constructor from next that takes two T and translates them into the corresponding mypair constructor, you must do this as follows:

 next (T first, T second) : mypair<T,A>(first, second) { } 

Again, this is usually applicable even without using templates.

+7
source

Complete solution if anyone is interested (thanks to Tyler)

 // class templates #include <iostream> using namespace std; template <class T, class A> class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} virtual A getmax (); }; template <class T, class A> A mypair< T, A>::getmax () { A retval; retval = a>b? a : b; return retval; } template <class T, class A> class next: mypair<T,A> { public: next (T first, T second) : mypair<T,A>(first, second) { } A getmax () { cout<<"WOO HOO"; } }; int main () { mypair <double,float> myobject(100.25, 75.77); next<double,float> newobject(100.25, 75.77); cout << newobject.getmax(); return 0; } 
+3
source

All Articles