Let's say I have a base template class Array:
template <class T = Point> class Array{
protected:
T* m_data;
int size;
public:
Array(); // constructor
Array(int n); // constructor
Array(const Array<T>& s_data); //Copy Constructor
// and so on..
}
And it has constructors and destructors. Also I have a derived template class NumericArray:
template <class T = int>
class NumericArray:public Array<T>{
public:
NumericArray();
NumericArray(int n);
NumericArray(const NumericArray<T>& s_data);
~NumericArray(); //destructor
};
Since I need to initialize the private members in the base class so I need to call the base constructors in the derived constructors. But how? I tried
template <class T>
NumericArray<T>::NumericArray(int n){
Array<T>(n); // it will think I create a Array<T> names n
}
template <class T>
NumericArray<T>::NumericArray(int n):Array(n){
// No field in NumericalArray called Array
}
Any idea?
A derived Java class can call a constructor in its base class using the super keyword. In fact, a constructor in the derived class must call the super's constructor unless default constructors are in place for both classes.
This is basically a default constructor for the basic types. We can use this technique in our template code to create default constructors. For any generic type, T, we can explicitly call its default constructor. Our Measurement template can now be constructed with any type that has a default constructor.
It is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. If we want the new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.
Combine your solutions, use the initializer list and the full name:
NumericArray<T>::NumericArray(int n)
: Array<T>(n)
{
}
Also, since they become a dependent name, fields of Array have to be accessed like this:
Array<T>::m_data; // inside a NumericArray method
Also, if it's not some experiment or homework, please use std::vector instead of pointer and size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With