0

I am trying to figure out how I can access the members of a base template class inside the derived class.

I have a base template class and a derived class as shown below.

template<int dim>
class base_class
{
 public:
  base_class() = default;               
  int member_ = 0;  
};

  template<int dim>
  class derived_class : public base_class<dim>
  {
  public : 
    derived_class() : base_class<dim>::member_(1) {}   
  };
 
int main(int argc, char* argv[])
{
        derived_class<2> dc;
    return 0;
}      

I read (https://stackoverflow.com/questions/4643074/why-do-i-have-to-access-template-base-class-members-through-the-this-pointer) that I must prepend the member of the derived class as

base_class<dim>::member_.

However the compiler gives the following error:

error: no type named ‘member_’ in ‘class base_class<2>’     derived_class() : base_class<dim>::member_(1) {}         

I do not understand why. Can anybody help me?

  • 3
    Let the base class initialize its own members, and let the derived class initialize its own members. It's not the responsibility of the derived class to initialize the base class (other than invoking the base class constructor). – Some programmer dude Jul 03 '23 at 12:35
  • 4
    It's not possible to initialise members of base class. Only the class that owns the member may initialise it and this is [unrelated to templates](https://godbolt.org/z/Kjh8Mr4fa). `base_class` should have a constructor that initialises `member_` as you want. – Yksisarvinen Jul 03 '23 at 12:38

1 Answers1

1

You should delegate the work of initialization of base member to base class constructor. One way of doing that is as shown below.

As can be seen, a parameterized ctor base_class<int>::base_class(int) has been added to initialize the base member. Then the newly added parametrized ctor is used in the member initializer list of the derived class.

template<int dim>
class base_class
{
 public:
  base_class() = default;               
  int member_ = 0;  
  //added this parameterized ctor
  base_class(int p): member_(p){}
};

template<int dim>
class derived_class : public base_class<dim>
{
  public : 
    //use the newly added parameterized ctor
    derived_class() : base_class<dim>(1)  
    {

    }    
};

working demo


I would also recommend reading How can I initialize base class member variables in derived class constructor?.

Jason
  • 36,170
  • 5
  • 26
  • 60