Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases do we need protected inheritance?

It is clear about public and private inheritance, but what about protected? Any example when we really need to use it and it gives us benefit?

like image 218
gunter Avatar asked Mar 31 '12 22:03

gunter


2 Answers

Protected inheritance is something whose meaning eludes me to this day.

This is Scott Meyers opinion (Effective C++, 3rd Edition) on protected inheritance :).

However, this page is interesting: Effective C++: discouraging protected inheritance?.

like image 174
Vincenzo Pii Avatar answered Nov 13 '22 22:11

Vincenzo Pii


The base-from-member idiom needs protected inheritance at times.

The problem that idiom addresses is the following: you sometimes need to initialize the base class with a member of the derived class, like in

struct foo
{
    virtual ~foo() {}

protected:
    foo(std::ostream& os)
    {
        os << "Hello !\n";
    }
};

struct bar : foo
{
    bar(const char* filename)
      : foo(file), file(filename) // Bad, file is used uninitialized
    {}

private:
    std::fstream file;
};

But file is constructed after foo, and thus the ostream passed to foo::foo is invalid.

You solve this with an auxiliary class and private inheritance:

struct bar_base
{
    std::fstream file;

protected:
    bar_base(const char* filename) 
      : file(filename) 
    {}   

    ~bar_base() {}
};

struct bar : private bar_base, public foo
{
    bar(const char* filename)
      : bar_base(filename), foo(file)
    {}
};

Now bar_base is constructed before foo, and the ostream passed to foo::foo is valid.

If you want file to become a protected member of bar, you must use protected inheritance:

struct bar : protected bar_base, public foo { ... }
like image 3
Alexandre C. Avatar answered Nov 13 '22 22:11

Alexandre C.