Search code examples
c++classinheritanceredefinition

(Redefinition error) Create multiple inherting classes from one baseclass in C++


Greetings oh mighty coders,

I am a beginner and in a bit of trouble here.

There is my baseclass (sensor.h):

class sensor
{
private:
   int sensor_id;
   string sensor_name;
   string sensor_type;
   float reading;

public:

   sensor();
   sensor(int, char*, char*);
   ~sensor();

/* Few extra methods here */

};

... and I want to create 4 other classes that inherit from my baseclass sensor (temperaturesensor, humiditysensor... and so on).

 #include "sensor.h"


class temperaturesensor:public sensor
{
public:
   Temperatursensor(int, char*,char*);
   ~Temperatursensor();

/* Few extra methods here */

};

Thing is: Every single one of these classes has to be in its own .cpp/.h file and then be included and used in my main.cpp.

using namespace std;
#include <xyz.h>
/* Other libaries here */
          ....
#include "temperaturesensor.h"
#include "humiditysensor.h"

int main()
{
    sensor* station[2];


    station [0] = new temperaturesensor(x,y,z);
    station [1] = new humiditysensor(x,y,z);
}

If I include one of them it's no biggie. However: If I use multiple ones I get an redefinition error.

error C2011: 'sensor': 'class' typeredefinition c:\users\name\desktop\project\sensor.h 14

error c2011: 'temperaturesensor' : 'class' typeredefinition 

What can I do to workaround this? Note that I am not allowed to use #pragma once

Sorry for my stupidity and thanks in advance!


Solution

  • You must use:

    #ifndef FILE_H
    #define FILE_H
    
    .. normal code here
    
    #endif
    

    or

    #pragma once
    

    but too, I think, that sensor schould be abstract class and you schould use virtual destructor. One more think is that array is numerate from 0.