For example, class Base
has two public methods: foo()
and bar()
. Class Derived
is inherited from class Base
. In class Derived
, I want to make foo()
public but bar()
private. Is the following code the correct and natural way to do this?
class Base { public: void foo(); void bar(); }; class Derived : public Base { private: void bar(); };
Although the private members are not accessible from the base class, they are inherited by them because these properties are used by the derived class with the help of non-private functions. Private members of the base class are not directly accessed, but derived by base class by derived class.
1) Public Inheritance: Protected members of Base class remain protected in Derived class. c. Public members of Base class remain public in Derived class. So, other classes can use public members of Base class through Derived class object.
Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class.
The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.
Section 11.3 of the C++ '03 standard describes this ability:
11.3 Access declarations
The access of a member of a base class can be changed in the derived class by mentioning its qualified-id in the derived class declaration. Such mention is called an access declaration. The effect of an access declaration qualified-id ; is defined to be equivalent to the declaration using qualified-id
So there are 2 ways you can do it.
Note: As of ISO C++ '11, access-declarations (
Base::bar;
) are prohibited as noted in the comments. A using-declaration (using Base::bar;
) should be used instead.
1) You can use public inheritance and then make bar private:
class Base { public: void foo(){} void bar(){} }; class Derived : public Base { private: using Base::bar; };
2) You can use private inheritance and then make foo public:
class Base { public: void foo(){} void bar(){} }; class Derived : private Base { public: using Base::foo; };
Note: If you have a pointer or reference of type Base which contains an object of type Derived then the user will still be able to call the member.
There is really no way to do what you want because if you derive publicly from Base
, a user of the class will always be able to:
Derived d; Base& b = d; b.bar();
It isn't "correct or natural" to make public base class functions inaccessible in a class derived publicy from the base class; instead, the base class interface should be refactored such that those functions are not public or are split into a separate class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With