简体   繁体   中英

C++ inheritance, and hiding unwanted inherited functions

I am trying to implement a QToolBar subclass, which has its items specified by a model, instead of added individually. This means a selection of functions to add/remove items (toolbar buttons), such as addAction shouldn't be publicly accessible.

What is the best way to inherit from this object, but make a selection of functions private?

My current best idea is to do like this:

class ToolbarView : public QToolBar
{
    Q_OBJECT
public:
    explicit ToolbarView(QWidget *parent = 0);

signals:

public slots:

private:

    void addAction (QAction *action) {Q_UNUSED(action)};
    QAction* addAction (const QString &text) {return QToolBar::addAction(text) ;}
    ...
    QAction* addSeparator() {QToolBar::addSeparator();}
    ... [list of about 10 of these]

};

So, redefining all the functions that should not be public, as private.

Is this a good idea, or are there better methods?

As long as you inherit publicly from QToolBar , you make it possible for a client code to treat your object as such and call for example the addAction member function. If you want to ensure that these functions are inaccessible, you'll have do this the other way :

  • Inherit privately from QToolBar
  • Publicly expose the functions you wish to expose (for example with using declarations)

If you want to stick with your initial solutions and inherit publicly from QToolbar :

  • Be aware that it doesn't guarantee base class functions won't be called
  • You should consider using using declarations to change the accessibility of the base class functions instead of hiding them

Maybe you could think of this

class ToolbarView : private QToolBar
{
    //...
}

In such case, all of accessible QToolBar will be with private access in your ToolbarView .

You are publically inheriting from QToolbar . How about changing that to private inheritance. That, is the class definition should begin as

    class ToolbarView : private QToolBar 
    {
    // good only if you want to 
    // make "most" of the public members of QToolBar private in ToolbarView
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM