Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Today I noticed that I basically never use protected methods in C++ code, because I rarely feel the need to call non-public methods of a parent. I do use protected in Java in the template method pattern, but since you can override private methods in C++, I don't need protected there, either.

So what are some real-world scenarios where I would want to use protected methods in C++ code?

(Note that I'm not too fond of implementation inheritance in general, that might explain a lot...)

share|improve this question
add comment

6 Answers

up vote 10 down vote accepted

Here is an example

class Base {
public:
  // other members ...

protected:
  ~Base() { }
};

Used as a non-polymorphic base class. But users will not be allowed to call delete baseptr; on it because the destructor is inaccessible. Since it has no virtual destructor, allowing people to do that would be undefined behavior. See "Virtuality" by Herb.

share|improve this answer
1  
What's up with you guys? Why was this downvoted? It's perfectly reasonable. If you don't understand it, please ask. If you feel like it's wrong, please explain. We're here to learn from your insights. –  sbi Mar 29 '11 at 17:16
    
Why -1? This is the first thing I thought of. –  GManNickG Mar 29 '11 at 17:17
1  
Constructors and Destructors are about the only uses I've seen. Note that gcc still emits a warning that the destructor is non-virtual on this one. –  Matthieu M. Mar 29 '11 at 17:19
    
+1 I also use protected method to apply some books advice: have a public interface with protected virtual functions, instead of public virtual functions. –  Klaim Mar 29 '11 at 22:01
add comment

One example that I use frequently is that in the Base Class of my object Hierarchy I will have a protected Logger. All of my base classes will need access to the Logger, but there is no reason to make that publicly accessible.

Also, if you're using the Template pattern, and you have a pre or post execute method on the base class, you may want to call the base implementation from the overriding method. If the base is only private (and can still be overwritten in C++), you won't be able to call the base implementation from the overriding method.

share|improve this answer
1  
Isn't the template pattern all about not having to call base class methods??? –  sbi Mar 29 '11 at 17:20
    
Point taken, but I wouldn't say it's 'all' about not having to call base class methods. In many situations I have object hierarchies implementing the template pattern that have multiple levels, each of which adds slightly more functionality/checks. In these cases, a Protected method would be necessary. –  BryanA Mar 29 '11 at 17:31
add comment

As many other features, protected allows you to break encapsulation to some extend. Breaking the pure OO concepts is usually done for several reasons

  1. achieving better performance (think inline),
  2. making code easier to understand, and, ironically,
  3. better encapsulation (friend allows you to restrict access to class members to a few friends)

and protected is just one of the tools in that box. You can use it if you want to give derived classes access to some parts of a class that should be hidden from the general public.

One case where I've used it is to make all constructors of a class protected, basically making that class abstract (you can't instantiate it except as a sub-object of a an object of a derived class).

share|improve this answer
add comment

Perhaps it was bad design, but I had it for something like this:

// much simplified, of course
class input_device // base class
{
public:
    virtual ~input_device() {}

    // normally would be private with public caller, etc.
    virtual void update() = 0; 

    template <typename Func>
    void register_callback(Func func)
    {
        mButtonPressSignal.connect(func);
    }

protected:
    void trigger_signal(unsigned button)
    {
        mButtonPressSignal(button);
    }

private:
    boost::signals2::signal<void(unsigned)> mButtonPressSignal;
};

Derived classes, in update(), could trigger the signal by calling trigger_signal(). But because that's all they should be able to do with the signal, the signal itself was left private. The trigger function was made protected because only the derived class should be able to trigger it, not anything at all.

share|improve this answer
add comment

Just an example I have used in the past. Protected methods are great for providing implementation-specific functions, whilst also allowing the base class to properly track things. Consider a base class that provides an overridable initialization function, but must also have state to determine if initialized:

class Base
{
private:
    bool m_bInitialized;
public:
    virtual void Initialize() = 0;

    void setInitialized() { m_bInitialized = true; };
    bool isInitialized() const { return m_bInitialized; };
}; // eo class Base

All is well and good here. Except when a derived class doesn't bother to call setInitialized() not least the fact that anybody can call it (we could make this protected here, and another reason to use protected methods!). I much prefer a class that makes use of virtual protected members:

class Base
{
private: 
    bool m_bInitialized;

protected:
    virtual void InitializeImpl() = 0;

public:

    void Initialize()
    {
        InitializeImpl();
        m_bInitialized = true;
    }; // eo Initialize

    bool isInitialized() const { return m_bInitialized; };
}; // eo class Base

In our new class, all initialization is still delegated to the derived class. Provided an exception as been thrown, we maintain the "this class is initialized" contract that our method says will happen.

share|improve this answer
add comment

"Public Methods" : A class can do this. "Protected Methods" : How a class can do this. "Private Methods" : How a class can do this, but "I'm paranoid and don't want anybody to know how I do it".

// burguers.hpp

class BurguerClass {
  private: void addSecretRecipeSauce();  

  protected: virtual void addBread();  
  protected: virtual void addSalad();  
  protected: virtual void addMeat();
  protected: virtual void addExtraIngredients();

  public: virtual void makeBurguer();  
}

class CheeseBurguerClass: public BurguerClass {
  protected: override void addBread();  
  protected: override void addSalad();  
  protected: override void addMeat();
  protected: override void addExtraIngredients();

  protected: virtual void addCheese();

  public: override void makeBurguer();
}

class RanchStyleBurguerClass: public BurguerClass {
  protected: override void addBread();  
  protected: override void addSalad();  
  protected: override void addMeat();
  protected: override void addExtraIngredients();

  public: override void makeBurguer();
}

class EastCoastVegetarianStyleBurguerClass: public BurguerClass {
  protected: override void addBread();  
  protected: override void addSalad();  
  protected: override void addMeat();
  protected: override void addExtraIngredients();

  public: override void makeBurguer();
}

So, a new cook (developer) arrives at your fast food restaurant. You teach it, you sell burguers (public methods), how to prepare the burguers (protected methods), but keep the "patented" secret recipe sauce to yourself.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.