user3334211
user3334211

Reputation: 1

Trying to implement a basic class in C++

I'm learning C++ and currently trying to create a very basic class representing a boat's length and weight... It seems I'm running into problems trying to split it into header and cpp files.

These are the simple files I'm working with...

Boat.h:

#ifndef BOAT_H_
#define BOAT_H_
class Boat{
public:
    Boat();
    Boat(int,int);

private:
    int length;
    int weight;
};

#endif /* BOAT_H_ */

Boat.cpp:

#include "Boat.h"

Boat::Boat(){
    length = 25;
    weight = 2500;
}

Boat::Boat(int newLength, int newWeight){
    length = newLength;
    weight = newWeight;
}

When compiling, I get errors in Boat.cpp about it being "first defined here". I've been following tutorials and trying to do like they do but I just can't seem to get this right. Here is the full error message. What am I missing?

C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/../Boat.cpp:4: multiple definition of `Boat::Boat()'
Main.o:C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/..//Boat.cpp:4: first defined here
Boat.o: In function `Boat':
C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/../Boat.cpp:4: multiple definition of `Boat::Boat()'
Main.o:C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/..//Boat.cpp:4: first defined here
Boat.o: In function `Boat':
C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/../Boat.cpp:9: multiple definition of `Boat::Boat(int, int)'
Main.o:C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/..//Boat.cpp:9: first defined here
Boat.o: In function `Boat':
C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/../Boat.cpp:9: multiple definition of `Boat::Boat(int, int)'
Main.o:C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/..//Boat.cpp:9: first defined here

Edit : I was including Boat.cpp in the main instead of Boat.h... Problem solved! Thank you!

Upvotes: 0

Views: 136

Answers (2)

tmaric
tmaric

Reputation: 5477

There is no way to be sure what you did, but I did manage to generate your error with this main function:

#include "Boat.h"
#include "Boat.cpp"

int main(int argc, const char *argv[])
{
    Boat b; 

    return 0;
}

compiled in the following way:

g++ -O0 -ggdb main.cpp  Boat.cpp -o main

which results exactly in the error you reported. Whatever you did - you seem to have tried to include the Boat.cpp file twice, and by doing so, you have doubled the definition of your Boat class.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

It seems that you included your boat.cpp file in the module where there is function main. You need to include only header boat.h in the module with main.

Upvotes: 0

Related Questions