1
votes

I searched through some of the other pages with this same error, but my code does not have any of their issues that I can find. It could just be that I am tired and slightly new to C++, if so sorry.

I have a parent class, shape.h, that has three derived classes; rectangle.h, triangle.h, and circle.h. The parent class is the one that gets the error "Redefinition of 'Shape'" on the third line. For the life of me I can not figure out what is wrong, other than possible the way I call the shape constructors from the derived classes. Please help, anymore information you need just let me know.

Shape.h:
#include < cmath>

class Shape
{
public:
    //constructors
    Shape();
    Shape(float a);
    Shape(float a, float b);

    //Returns
    float area();
    float perimeter();

protected:
    float base;
    float height;
    float radius;
};

Shape.cpp:
#include "Shape.h"

//constructors
Shape::Shape()
{
    base = 0;
    height = 0;
    radius = 0;
}

Shape::Shape(float a)
{
    radius = a;
}

Shape::Shape(float a, float b)
{
    base = a;
    height = b;
}

//returns
float Shape::area()
{
    return 0;
}

float Shape::perimeter()
{
    return 0;
}

All derived classes are the same except different calculations , so here is Circle.h:
#include "Shape.h"

class Circle: public Shape
{
public:
    //constructors
    Circle();
    Circle(float a);

    //Returns
    float area();
    float perimeter();

private:

};

Circle.cpp:
#include "Circle.h"

//constructors
Circle::Circle():Shape()
{

}

Circle::Circle(float a):Shape(a)
{

}

//returns
float Circle::area()
{
    return (3.14 * pow(radius,2));
}

float Circle::perimeter()
{
    return (2 * 3.14 * radius);
}
1

1 Answers

1
votes

In Circle.cpp Shape.h indirectly included twice and causes mentioned compilation error.

Add include guard to your headers. E.g. Shape.h should be:

#ifndef SHAPE_H
#define SHAPE_H

// Put your Shape class here 

#endif

The other approach is to use #pragma once at the beggining of Shape.h if your compiler supports it.