Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance of templated class members in constructor

I posted a very similar question and got my answer. I'm now facing the same issue with the constructor.. How would one write the constructor for T2 ?

template<typename T>
class T1
{
    public:
      T1(int t) : m_t(t) {}

    protected:
    int m_t;
};

template<typename T>
class T2 : public T1<T>
{
    public:
      T2(int t) : m_t(t) {} // error

      int get()
      { return this->m_t; }

    protected:
};
like image 809
user2287453 Avatar asked Jan 26 '26 13:01

user2287453


1 Answers

You need to call the base class constructor in the initializer list for T2:

T2(int t) : T1<T>(t) {}

T2<T>'s constructor will call T1<T>'s constructor, which will initialize T1<T>::m_t

like image 97
Charles Salvia Avatar answered Jan 29 '26 02:01

Charles Salvia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!