Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: redefinition of class

Here's my code:

// in main.cpp

#include "iostream"
#include "circle.cpp"
#include "rectangle.cpp"
#include "shape.cpp"

using namespace std;

int main() {
    Shape shapes[10];

    for (int i = 0; i < 10; i++){
        if (i % 2)
            shapes[i] = Circle(5);
        else
            shapes[i] = Rectangle(10, 10);

        cout << shapes[i].getArea();
    }

    return 0;
}


// in circle.cpp

#include "shape.cpp"

class Circle : public Shape {
    private:
        int radius;
        static const double PI = 3.14159265358979323846;

    public:
        Circle (int radius) : radius(radius) {}

        virtual int getArea() const {
            return PI * radius*radius;
        };

        virtual int setRadius(int radius){
            radius = radius;
        }
};


// in rectangle.cpp

#include "shape.cpp"

class Rectangle : public Shape {
    private:
        int width;
        int height;

    public:
        Rectangle(int width, int height) : width(width), height(height){}

        virtual int getArea() const {
            return width * height;
        }

        virtual void setWidth(int width){
            this->width = width;
        }

        virtual void setHeigth(int height){
            this->height = height;
        }
};


// in shape.cpp

class Shape {
    public:
        virtual int getArea() const = 0;
};

When compiling, I get this error:

error: redefinition of 'class Shape'

How can I fix this?

like image 605
Aviv Cohn Avatar asked Oct 03 '14 12:10

Aviv Cohn


2 Answers

You should structure your code between .h (headers) and .cpp files (implementation).

You should include header files: .h Never include .cpp files. (Unless you know what you do, and that would be in really rare cases).

Otherwise you're ending compiling several times your class, and you get the error your compiler is telling you: 'redefinition of class...'

An additional protection against this error are Include Guards, or Header Guards.

Most compilers support something of the like #pragma once that you write at the top of .h files to ensure it is compiled only once.

If the pragma is not available for your compiler, then there is the traditionnal Include/Header guard system:

#ifndef MYHEADEFILE_H
#define MYHEADEFILE_H

// content of the header file

#endif
like image 74
Stephane Rolland Avatar answered Sep 20 '22 13:09

Stephane Rolland


Your main.cpp includes files which include shape.cpp, which ends up being included multiple times. You can avoid this by wrapping your included files with a check for a definition:

#ifndef SHAPE_CPP
#define SHAPE_CPP

//file contents

#endif
like image 36
James Thorpe Avatar answered Sep 19 '22 13:09

James Thorpe