Persistent redefinition error

Hi,
I have edited and re-edited my code but this error never seems to go away:

The error is:
error: re-definition of 'rectangle::rectangle(double, double)'

Here's my class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef RECTANGLE_H
#define RECTANGLE_H
class rectangle
{
    private:
        double length, width;   //private member variables

    public:
        rectangle() = default;    //constructor
        rectangle(double x, double y):length(x),width(y){}
        double area();
        double perimeter();
        double diagonal();
};
#endif // RECTANGLE_H


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "rectangle.h"
#include <cmath>
using namespace std;

rectangle::rectangle(double x, double y)
{
    length = x;
    width = y;
}

double rectangle::area(){
    return length*width;
}

double rectangle::perimeter(){
    return 2*(length * width);
}

double rectangle::diagonal(){
    return hypot(length,width);
}




Here's my main function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include "rectangle.h"

using namespace std;

int main(){
 
  rectangle rect(4.0,4.0);

   cout<<rect.area()<<endl;
  
   cout<<rect.perimeter()<<endl;

   return 0;
}
Last edited on
Remove the definition of rectangle::rectangle(double, double) from the header file.
It is defined it in the implementation file.

And make the class const-correct. http://msdn.microsoft.com/en-us/library/6ke686zh.aspx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef RECTANGLE_H
#define RECTANGLE_H
class rectangle
{
    private:
        double length, width;   //private member variables
        // invariant: lenth and width are not negative   

    public:
        rectangle() = default;    //constructor
        rectangle(double x, double y) ; // :length(x),width(y){} // *******
        double area() const ; // ****
        double perimeter() const ; // ****
        double diagonal() const ; // ****
};
#endif // RECTANGLE_H 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "rectangle.h"
#include <cmath>
// using namespace std; // avoid ****

rectangle::rectangle(double x, double y) {
// { // use a consistent brace-style
 
    // check if x or y is less than zero?

    length = x;
    width = y;
}

double rectangle::area() const {
    return length*width;
}

double rectangle::perimeter() const {
    return 2*(length * width);
}

double rectangle::diagonal() const {
    return std::hypot(length,width);
}


You might want to verify that length and width are non-negative, and take corrective action in the constructor if negative values are passed.
You've implemented rectangle::rectangle(double, double) twice. Remove one of them.
thank you JLBorges
Topic archived. No new replies allowed.