Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: Question on access specifier in inheritance

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading