Home > Blockchain >  C : Question on access specifier in inheritance
C : Question on access specifier in inheritance

Time:12-04

Here's the following code.

#include <iostream>
using namespace std;

class B {
    private:
        int a=1;
    protected:
        int b=2;
    public:
        int c=3;
};

class D : protected B { // clause 1
};

class D2 : public D { // clause 2
    void x() {
       c=2;
    }
};

int main() {
    D d;
    D2 d2;
    cout << d2.c; // clause 3 Error due to c being protected
    return 0;
}

Note:

  1. Clause 1 would make c to be protected.
  2. Clause 2 would make c (protected in clause 1) to be public again.
  3. Why clause 3 failed?

CodePudding user response:

Your notes are not entirely correct:

  1. private inheritance makes public, protected and private members be private in the derived class
  2. protected inheritances makes public and protected members be protected in the derived class, and private members stay private
  3. public inheritance changes nothing to the derived members' access.

c is protected in D and still protected in D2 because of the public inheritance. There is no way to cheat visibility. What you assume would break logic. Visibility only goes downwards, not up.

CodePudding user response:

The type of inheritance you use does not affect the protection level of members in the parent class. It only changes the protection level of those members in the child class.

When you define class D : protected B it is equivalent to defining class D like this:

class D
{
protected:
  int b=2;
  int c=3;
};

Then when you define class D2 : public D it is equivalent to defining class D2 like this:

class D2
{
protected:
  int b=2;
  int c=3;
};
  • Related