C ++ Inheritance: Defining Coverage 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;
}

Bye this?

#include <stdio.h>

class A {
public:
    int a;
};

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

int main() {
    return 0;
}

In both cases, we have one public and one private variable named ain class B.


edited now!

+5
source share
4 answers

In both cases, we have one publication and one personal variable named a in class B.

No, it is not.

In the first case, you cannot have two identifiers with the same name in the same scope. Although in the second case it B::ahides A::a, and to access A::ayou need to fully define the name:

b.a = 10; // Error. You can't access a private member.
b.A::a = 10; // OK.
+15
source

B::a A::a . , , , .

a , .

+3

, . , , a integer, A:: a B. , , .

, mangaling: . .

, , - , - , -, .

b:

class b {

int a;
public:
int a;

void myMethod()
{
 a = 10; //what a should the compiler use? Ambiguous, so the compiler sez BZZT.
}

}

:

class A
{
public: 
int a;
}

class B: public A
{
private:
int a;

void someMethod()
{
 a = 10; //implied that you are using B::a (which may be a programmer error)

}

}
0

B , ++ (public/private/protected). - ++ . B "public a" "private a", B::a A::a.

/ , .

0

All Articles