Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to do make a public member in a base class private in a derived class, like this:

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

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

But apparently "using" can't be used that way. Is there any way to do this in C++?

(I can't use private inheritance because there are other members and functions of A that must still be public.)

like image 493
Colen Avatar asked Sep 02 '10 01:09

Colen


People also ask

Can derived classes access private variables?

Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.

Can derived classes access public members?

As a quick refresher, public members can be accessed by anybody. Private members can only be accessed by member functions of the same class or friends. This means derived classes can not access private members of the base class directly! This is pretty straightforward, and you should be quite used to it by now.

Can we declare public/private protected in base class?

No, we cannot declare a top-level class as private or protected.

Does a derived class inherit private members?

The derived class doesn't "inherit" the private members of the base class in any way - it can't access them, so it doesn't "inherit" them.


2 Answers

Yes, using declaration technically allows you to do so.

You have to use using A::y instead of using y

However please seriously evaluate if doing this makes a design sense.

Few observations:

  1. Your class should not have public data. That should be avoided as far as possible. If you stick to this design principle, you may not have a need to make it private in derived class.

  2. Stick to LSP. If a base class has public method, and unless you are doing private inheritance, clients will be confused if the derived class makes the base class method private with such using declarations.

like image 182
Chubsdad Avatar answered Oct 12 '22 03:10

Chubsdad


Short answer: no. Liskov substitution and the nature of public inheritance demands that everything that you can do with an A (i.e. its public members) can also be done by B. That means you can't hide a public method.

If you're trying to hide public fields, there isn't much you can do. To "hide" public methods, you could do something like:

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
};
like image 29
munificent Avatar answered Oct 12 '22 02:10

munificent