0

I have the following class structure

// shape.h
enum colors {RED=0, BLUE, GREEN};

class Shape {
    public:
        colors col;
        void setColor(colors c) {
            col = c;
        }
};

// circle.h
#include "Shape.h"
class Circle: public Shape {};

// rect.h
#include "Shape.h"
class Rect: public Shape {};

In my main.cpp I include both, Circle and Rect.

#include <iostream>
#include "Rect.h"
#include "Circle.h"

int main() {
    return 0;
}

Unfortunately, this leads to an error: error: multiple definition of 'enum colors', because they are both inheriting from Shape. I am new to C++ and wonder what is the best practice to avoid/solve this?

Sebastian Dine
  • 815
  • 8
  • 23
  • You forgot include guards. – n. m. could be an AI Jun 10 '23 at 09:43
  • 1
    A simple way would be to move the `enum colors { RED = 0, BLUE, GREEN };` to the `public` section of the `Shape` class. Then use (say) `Shape::BLUE` when you want to refer to a particular colour. – Adrian Mole Jun 10 '23 at 09:46
  • Add #pragma once to all your headers files (or use #define and #ifndef to define include guards) – Pepijn Kramer Jun 10 '23 at 09:46
  • 1
    This is what [include guards](https://www.learncpp.com/cpp-tutorial/header-guards/) are for. – john Jun 10 '23 at 09:46
  • 1
    Does this answer your question? [C++ Header File redefinition Error](https://stackoverflow.com/questions/22871224/c-header-file-redefinition-error), [C++ class redefinition error - Help me understand headers and linking](https://stackoverflow.com/questions/14485215/c-class-redefinition-error-help-me-understand-headers-and-linking) – fabian Jun 10 '23 at 09:58
  • @AdrianMole -- that's a simple solution to this particular error, but it doesn't fix the problem of missing include guards. – Pete Becker Jun 10 '23 at 14:49

1 Answers1

3

You can use Include_guard to avoid multiple inclusions:

#ifndef SHAPE_H
#define SHAPE_H
enum colors {red,green,blue};

class Shape {
    public:
        colors col;
        void setColor(colors c) {
            col = c;
        }
};

#endif
Pulkit Sharma
  • 390
  • 2
  • 14
  • Addition to the answer: in case using VC++, simply put ```#pragma once``` at the top of your *.h or *.hpp file which does exactly the same effect of using macros. – Iman Abdollahzadeh Jun 10 '23 at 10:05
  • If you want to use compiler-specific remedies, you can use `#pragma once`; it isn't part of the standard, and it has subtle problems (i.e., it can't be reliably implemented, although it works for most build system configurations). In short: use normal include guards, as the code in this answer does. – Pete Becker Jun 10 '23 at 14:48