Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

c++ - How to publicly inherit from a base class but make some of public methods from the base class private in the derived class?

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();
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...