Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance: scoping and visibility of members

Can you explain why this is not allowed,

#include <stdio.h>

class B {
private:
    int a;
public:
    int a;
};

int main() {
    return 0;
}

while this is?

#include <stdio.h>

class A {
public:
    int a;
};

class B : public A{
private:
    int a;
};

int main() {
    return 0;
}

In both the cases, we have one public and one private variable named a in class B.


edited now!

like image 819
Moeb Avatar asked Jun 13 '10 19:06

Moeb


2 Answers

In both the cases, we have one public and one private variable named a in class B.

No, thats not true.

In the first case, you can't have two identifiers with the same name in the same scope. While in the second case, B::a hides A::a, and to access A::a you have to fully qualify the name:

b.a = 10; // Error. You can't access a private member.
b.A::a = 10; // OK.
like image 84
Khaled Alshaya Avatar answered Nov 11 '22 15:11

Khaled Alshaya


Because B::a hides A::a in the second example. You can still access it, but it needs explicit qualification for the compiler to figure out you are asking for the member of parent class with the same hame.

In the first example both a's are in the same scope, while in the second example the scopes are different.

like image 35
Nikolai Fetissov Avatar answered Nov 11 '22 13:11

Nikolai Fetissov