Jon
Jon

Reputation: 8531

C++ - Inherit Virtual Function Implementation

If I am to inherit from a class, would I have to define all of its virtual and pure virtual functions?

For example, I have a derived class that is inheriting from QAbstractItemModel. QAbstractItemModel has the following pure virtual functions. If my derived class is not going to use the index() and parent() method, would I need to implement it?

//qabstractitemmodel.h
virtual QModelIndex index(int row, int column,
                              const QModelIndex &parent = QModelIndex()) const = 0;
virtual QModelIndex parent(const QModelIndex &child) const = 0;
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const = 0;
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const = 0;
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const = 0;

Upvotes: 1

Views: 2332

Answers (2)

Ben Cottrell
Ben Cottrell

Reputation: 6130

You don't have to implement anything at all in your derived class, but that derived class will still be abstract if you leave any of the pure virtual member functions without an implementation (In other words, you won't be able to instantiate an object of that class).

Edit: Something else to consider - If your base class contains pure virtual functions which your derived classes do not want/need, maybe worth looking at an alternative design? Perhaps using multiple base classes which declare different parts of the interfaces.

If index() and parent() don't apply to all of the derived classes of QAbstractItemModel then I'd argue those functions possibly don't belong to QAbstractItemModel really

Upvotes: 3

Asaf
Asaf

Reputation: 4407

Yes. Declaring a method as pure virtual (' = 0') means that any concrete subclass (which can be instantiated) has to implement them.

Upvotes: 2

Related Questions