开发者

C++ : restrict access to the superclass' methods selectively?

开发者 https://www.devze.com 2023-02-15 22:32 出处:网络
This is an interview question. I am not a C++ expert yet so i need some help in finding the answer to this question ( i first want to understand the question...is it a valid question?)

This is an interview question. I am not a C++ expert yet so i need some help in finding the answer to this question ( i first want to understand the question...is it a valid question?)

Question:

Suppose I have a class B that derives fr开发者_如何学Goom class A and I wanted to reuse some, but not all of the methods of A. How would I restrict access to the superclass' methods selectively?

thanks!


I assume that

  1. you cannot change the definition of A
  2. you want to select which methods from A should be accessible from a B object.

The using directive solves your problem. Example:

class A
{
public: // or protected for that matter
    void foo();
    void bar();
};

class B : private A // or protected, depending on whether
                    // you want subclasses of B to expose
                    // some methods from A themselves
{
public:
    using A::foo;
};

makes foo usable from class B, but not bar. But as a caveat, note that using A::foo will expose all overloads of foo.


The answer they probably want to hear is that you can put the methods to be reused in the protected section of the base class, the methods which should not be visible to the derived classes should go into the private section.

However, taking a step back, you might be able to score extra points by pointing out that there might be better measures for reusing code, depending on what the functions do (such as using free functions which are not visible in a header file).

0

精彩评论

暂无评论...
验证码 换一张
取 消