Search code examples
c++functionvirtualdeclaration

multiple declaration error- virtual functions


I have observer.h , client.h and field.h files.

In observer.h there is Subject class which has

// observer.h

class Subject  {
public:
 virtual ~Subject(){};
 Subject(){};
 virtual void Attach(Observer*);
 virtual void Detach(Observer*);
 virtual void Notify(bool _value);
 virtual bool getCheckedIn(){};
private:
 vector < Observer* >  _observers;
};

 

#ifndef CLIENT_H
#define CLIENT_H

#include "Field.h"

class Client : public Subject {
public:
 Client(string _name, Field *_field) : client_name(_name) ,field(_field) , checked_in(false) {}

 void setCheckedIn(bool _value){
  checked_in = _value;
  Notify(_value);
 }

 void enterRow(string _row_name){
  field->deneme();
  setCheckedIn(true);
 }

 bool getCheckedIn(){ return checked_in;}
private:
 bool checked_in;
 string client_name;

 Field *field;

};

#endif // CLIENT_H

 

#ifndef Field_H
#define Field_H
#include "CreateRow_absFac.h"
#include "observer_pattern.h"
#include <vector>
#include <string>
using namespace std;

// Template Class 
class Field{
public:
 Field(); 
 // Template method 
 void field_creator();
 virtual void setAbstractRow() = 0;
protected:
 FarmFactory *abstract_row1;
 FarmFactory *abstract_row2;
 FarmFactory *abstract_row3;

 Rows *row1 ;
 Rows *row2 ;
 Rows *row3 ;
 Sensor sensor1; 
};

When compiled , got this error :

ld: duplicate symbol Subject::Notify(bool) in /Users/barisatamer/Desktop/se311/PROJECT/build/PROJECT.build/Debug/PROJECT.build/Objects-normal/x86_64/Field.o and /Users/barisatamer/Desktop/se311/PROJECT/build/PROJECT.build/Debug/PROJECT.build/Objects-normal/x86_64/main.o

If I remove virtual functions it compiles without error. What is the problem with virtual functions ?


Solution

  • We can't actually see it here, but the problem is probably that you defined Subject::notify(bool) in a header file (your observer.h just declares it, it doesn't define it) and you included that header file in both Field.cpp and main.cpp, so you get multiple definitions. The fix is to move the definition into a source file so its only defined once.

    General rule -- DECLARE things in header files, DEFINE them in non-header source files. Note that include guards are irrelevant here -- they prevent something being declared multiple times in a single compilation unit, but what's needed is to avoid defining something multiple times in different compilation units.