Should you ever use protected member variables?

后端 未结 10 1729
星月不相逢
星月不相逢 2020-12-02 07:53

Should you ever use protected member variables? What are the the advantages and what issues can this cause?

10条回答
  •  有刺的猬
    2020-12-02 08:27

    Most of the time, it is dangerous to use protected because you break somewhat the encapsulation of your class, which could well be broken down by a poorly designed derived class.

    But I have one good example: Let's say you can some kind of generic container. It has an internal implementation, and internal accessors. But you need to offer at least 3 public access to its data: map, hash_map, vector-like. Then you have something like:

    template 
    class Base
    {
       // etc.
       protected
       TContainer container ;
    }
    
    template 
    class DerivedMap     : public Base >      { /* etc. */ }
    
    template 
    class DerivedHashMap : public Base > { /* etc. */ }
    
    template 
    class DerivedVector  : public Base >        { /* etc. */ }
    

    I used this kind of code less than a month ago (so the code is from memory). After some thinking, I believe that while the generic Base container should be an abstract class, even if it can live quite well, because using directly Base would be such a pain it should be forbidden.

    Summary Thus, you have protected data used by the derived class. Still, we must take int o account the fact the Base class should be abstract.

提交回复
热议问题