0

So if I have a following class Super:

class Super {
public:
    string member = "bla bla";
    void doSth() { cout << member; }
};

And a class Sub that inherits Super:

class Sub : Super {
public:
    string member2 = "bla bla 2";
};

Than, when I have a Sub object, I can't reach members of Super even thought they're public.

using namespace std;
int main(){
    Sub sub;
    cout << sub.member2 << endl;
    cout << sub.member << endl; // error: public Super::member is inaccessible 
    sub.doSth(); // error: public Super::doSth() is inaccessible 
}

But why if they're public? Or am I doing something wrong?

Scarass
  • 914
  • 1
  • 12
  • 32
  • 5
    you have `private` inheritance, but you want `public` inheritance – 463035818_is_not_an_ai Jul 13 '17 at 15:02
  • thanks, that's it, I didn't about for that – Scarass Jul 13 '17 at 15:04
  • 1
    If you are going to ask questions about inheritance in C++, it would be a good idea to use the terms `base` and `derived`, rather than `superclass` and `subclass`. –  Jul 13 '17 at 15:05
  • You may want to read these links: https://isocpp.org/wiki/faq/basics-of-inheritance , https://isocpp.org/wiki/faq/strange-inheritance , https://isocpp.org/wiki/faq/private-inheritance – Jesper Juhl Jul 13 '17 at 15:09

1 Answers1

5

You are inheriting from Super privately. If you do not mention the access level for inheritance, that is the default for classes in C++. However, note that structs have the default set to public.

Change your code to

class Sub : public Super {
public:
    string member2 = "bla bla 2";
};

And then member will be visible

Curious
  • 20,870
  • 8
  • 61
  • 146