Search code examples
c++oopinheritancepolymorphismvirtual

Can I exclude a base class member from the derived class?


Let's say I have a class called CWindow:

class CWindow
{
public:
    virtual bool Create();
};

In the derived class CMyWindow, I want to overload the Create(void) method to Create(int someParam), BUT, I do not want the user to be able to call the Create(void) method, only the Create(int someParam). Is this possible? Could I do:

class CMyWindow : public CWindow
{
private:
    bool Create();
public:
    virtual bool Create(int someParam);
};

Is this valid? Will it basically make the formerly public member of CWindow be a private member of CMyWindow?

I imagine if it IS possible to 'exclude' a member from a class, that this is closest to doing so, because AFAIK there is no magic youcantbeamember keyword in C++

My best guess is that no, you cannot do this. But I'm just hoping because I would like to avoid making a base class that has everything except for the Create() member, and deriving CWindow and CMyWindow from CWindowBase.


Solution

  • You can actually do this, and it will work as expected. The only problem is that a CMyWindow is still a CWindow, which allows Create():

    CMyWindow w;
    w.Create(); // does not compile
    static_cast<CWindow>(w).Create(); // compiles just fine
    

    If you don't want to allow this at any cost then you have to make CWindow::Create abstract and possibly provide the current implementation (if any) as a protected member that derived classes can call explicitly:

    class CWindow
    {
    public:
        virtual bool Create() = 0;
    protected:
        bool DefaultCreateImplementation();
    };
    
    class CNormalWindow : public CWindow
    {
    public:
        bool Create() { return DefaultCreateImplementation(); }
    }
    
    class CMyWindow : public CWindow
    {
    private:
        virtual bool Create(); // declared but not defined
                               // if called by accident will produce linker error
    public:
        virtual bool Create(int someParam);
    };