A simple example how to use class templates in combination with inheritance.
A simple example how to use class templates in combination with inheritance. The this->
in the member function calculate
of the class Rectangle
becomes crucial, otherwise the compiler won’t find the location of the function.
#include <iostream> using namespace std; template<class dataType> class Area { private: dataType area = 0.1; public: void set_area(const float _area) {area = _area;}; dataType get_area() const {return area;}; void printArea() {cout << area << endl;}; }; template<class dataType> class Rectangle : public Area<dataType> { public: void set_lengthA(const dataType _lengthA) {lengthA = _lengthA;}; void set_lengthB(const dataType _lengthB) {lengthB = _lengthB;}; void calculate() {this->set_area(lengthA * lengthB);}; private: dataType lengthA = 0.2; dataType lengthB = 0.2; }; int main() { Rectangle<float> myRect; myRect.set_lengthA(0.2); myRect.set_lengthB(0.3); myRect.calculate(); myRect.printArea(); return 0; }