0

So, the simplest case:

class Parent
{
    protected:
        int p;
};

class Child : public Parent
{
    public:
        int getP() const {
            return p;
        }
};

Why are we using public here? I've seen it many times, but still don't understand what it does. It seems to me that Child can get access to protected attributes of Parent in any case.

S. Ellis
  • 113
  • 1
  • 9
  • 2
    ***Why are we using public here?*** Because a class is private by default. – drescherjm Aug 16 '20 at 12:48
  • Which `public` are you asking about? There are two. – interjay Aug 16 '20 at 12:50
  • Non-public inheritance is very rarely useful. It limits visibility of that relation the same way as it does for class members, so with `class Derived: protected Base` you cannot do `Base* b = new Derived` in `main()`, but you can do that `Derived` and it's derived classes. I cannot give any good reason for that off the top of my head, unless you want to only inherit members (in a hidden manner) and forbid polymorphism. – Yksisarvinen Aug 16 '20 at 12:50
  • 1
    I now think the OP is talking about this line `class Child : public Parent` which can be more confusing than the other usage of public. – drescherjm Aug 16 '20 at 12:54
  • 2
    @Yksisarvinen Related: [When should I use C++ private inheritance?](https://stackoverflow.com/q/656224/580083). – Daniel Langr Aug 16 '20 at 13:22

0 Answers0