开发者

Can I keep a certain functions from being inherited in C++

开发者 https://www.devze.com 2023-03-09 06:54 出处:网络
Sample code #include <iostream> using namespace std; class Base { public: virtual void Func() { cout << \"\\nIn base func\";

Sample code

#include <iostream>

using namespace std;

class Base
{
public:
    virtual void Func()
    {
        cout << "\nIn base func";
    }
};

class Derived : public Base
{
public:
    void Func()
    {
        cout << "\nIn derived";
    }
};

class Derived2 : public Derived
{
public:
    void Func()
    {
        cout << "\nIn derived2";
    }
};

int main()
{
    Base* lnewbase = new Derived2();

    lnewbase->Func();

    return 0;
}

As an example, in the above code, 开发者_运维知识库I do not want Func() of Derived to be inherited (seal in C#) which is why there is no virtual keyword although I am aware that it does not change anything in this case. Is there any way to disallow that function to be inherited while making sure it remains a public method?


No; C++ has no equivalent to C#'s sealed modifier.


There is nothing you can do.

Once you make a function in a base class virtual, there's nothing that can be done to get rid of that aspect of it. I can only think of a few things to almost get around it:

  • Don't make it virtual;
  • Make a new, public, non-virtual function in Derived that does what you need.

However, in either case, Derived2 will still be able to make its own version of Func(), which will give you the same problem.

0

精彩评论

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