Scarass
Scarass

Reputation: 944

Can't acces super class public members with sub class variable

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?

Upvotes: 0

Views: 903

Answers (1)

Curious
Curious

Reputation: 21510

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

Upvotes: 5

Related Questions