Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call constructor of a template base class in a template derived class?

Tags:

c++

templates

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?

like image 958
Partita Avatar asked Jul 31 '14 16:07

Partita


People also ask

How do you call a base class constructor from a derived class?

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.

Can template class have constructor?

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.

Can a template base class derived?

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.


1 Answers

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.

like image 91
erenon Avatar answered Sep 27 '22 19:09

erenon