Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Multiple inheritance with interfaces?

Greetings all,

I come from Java background and I am having difficulty with multiple inheritance.

I have an interface called IView which has init() method.I want to derive a new class called PlaneViewer implementing above interface and extend another class. (QWidget).

My implementation is as:

IViwer.h (only Header file , no CPP file) :

#ifndef IVIEWER_H_
#define IVIEWER_H_

class IViewer
{
public:
  //IViewer();
  ///virtual
  //~IViewer();
  virtual void init()=0;
};

#endif /* IVIEWER_H_ */

My derived class.

PlaneViewer.h

#ifndef PLANEVIEWER_H
#define PLANEVIEWER_H

#include <QtGui/QWidget>
#include "ui_planeviewer.h"
#include "IViewer.h"
class PlaneViewer : public QWidget , public IViewer
{
    Q_OBJECT

public:
    PlaneViewer(QWidget *parent = 0);
    ~PlaneViewer();
    void init(); //do I have to define here also ?

private:
    Ui::PlaneViewerClass ui;
};

#endif // PLANEVIEWER_H

PlaneViewer.cpp

#include "planeviewer.h"

PlaneViewer::PlaneViewer(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
}

PlaneViewer::~PlaneViewer()
{

}

void PlaneViewer::init(){

}

My questions are:

  1. Is it necessary to declare method init() in PlaneViewer interface also , because it is already defined in IView?

2.I cannot complie above code ,give error :

PlaneViewer]+0x28): undefined reference to `typeinfo for IViewer' collect2: ld returned 1 exit status

Do I have to have implementation for IView in CPP file (because all I want is an interface,not as implementation) ?

like image 352
Ashika Umanga Umagiliya Avatar asked Jun 11 '10 05:06

Ashika Umanga Umagiliya


1 Answers

A good way to think about interface classes is that they specify what methods derived classes MUST implement.

Is it necessary to declare method init() in PlaneViewer interface also , because it is already defined in IView?

The quick answer is that yes you must implement the init method in IViewer because in the base class the method is declared as pure virtual. This means that any derived class MUST provide its own implementation of that method as there is no base class method implemented.

2.I cannot complie above code ,give error :

PlaneViewer]+0x28): undefined reference to `typeinfo for IViewer' collect2: ld returned 1 exit status

This is a g++ compiler error that indicates (as stated above) that you have a derived class from a base that has a pure virtual function and that the derived class does not implement the pure virtual method, as it must.

Oh and it should also be noted that you are not having an issue with multiple inheritance, the problem would still exist if only IViewer and PlaneViewer were involved.

like image 83
radman Avatar answered Sep 29 '22 06:09

radman