Can I make the public member variable private in a derived class?

I want to make a public member in the base class private in a derived class, for example:

class A {
public:
    int   x;
    int   y;
};

class B : public A {
    // x is still public
private:
    // y is now private
    using y;
};

But, apparently, "use" cannot be used in this way. Is there any way to do this in C ++?

(I cannot use personal inheritance because there are other members and functions of A that should still be publicly available.)

+5
source share
2 answers

: . , , A (.. ), B. , .

fields, . "" , - :

class B {
    // x is still public
    int x() { return a.x(); }
private:
    A a;
    // y is now private since you didn't add a forwarding method for it
};
+3

, technically .

using A::y using y

, , , .

:

  • . , . , .

  • LSP. , , , .

+3

All Articles