Try to search your question here, if you can't find : Ask Any Question Now ?

C++ – Accessing protected members of base class template

HomeCategory: stackoverflowC++ – Accessing protected members of base class template
Avatarbhawya asked 5 months ago

I have noticed that C++ templates don’t allow derived classes to access protected members of base classes without using this->member or Base<T>::member. In a regular class I can just write:

class Base{
  public:
  Base(){
    k = 4;
  }
  protected:
  int k;
};

class Derived : public Base{
  public:
  void foo(){
    std::cout << k << 'n';
  }
};

No errors so far. But then if I make Base and Derived class templates, I can’t access k without being more explicit:

template<class T>
class Base{
  public:
  Base(){
    k = 4;
  }
  protected:
  int k;
};

template<class T>
class Derived : public Base<T>{
  public:
  void foo(){
    std::cout << k << 'n'; //error
  }
  void bar(){
    std::cout << this->k << 'n'; //ok
  }
  void bar2(){
    std::cout << Base<T>::k << 'n'; //ok
  }
};

So why does this happen? Is there any way around it? I have a project where I’m frequently accessing protected members of base classes and the fact that I constantly need to dereference this is a) annoying to type and b) makes the code less readable.

1 Answers
Best Answer
AvatarFernando answered 5 months ago
Your Answer

5 + 6 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com