I have an assignment that requires me to write overloaded constructors for a class (Car) in c . I keep getting a redefinition error but cannot pinpoint what's causing it. I feel that it could possibly have to do with the code being separated out between two separate files (Car.h, Car.cpp) but I'm not sure.
Here is the class in Car.h:
class Car {
public:
Car(){};
Car(string userMake, string userModel, double userPrice){};
string getMake();
string getModel();
double getPrice();
private:
string make;
string model;
double price;
};
Here are the constructors throwing the error in Car.cpp:
Car::Car () {
make = "DeLorean";
model = "Alpha5";
price = 145000;
}
Car::Car (string userMake, string userModel, double userPrice) {
make = userMake;
model = userModel;
price = userPrice;
}
Here are the compiler errors:
Car.cpp:6:1: error: redefinition of ‘Car::Car()’
6 | Car::Car () {
| ^~~
In file included from Car.cpp:1:
Car.h:10:9: note: ‘Car::Car()’ previously defined here
10 | Car(){};
| ^~~
Car.cpp:14:1: error: redefinition of ‘Car::Car(std::string, std::string, double)’
14 | Car::Car (string initMake, string initModel, double initPrice) {
| ^~~
In file included from Car.cpp:1:
Car.h:11:9: note: ‘Car::Car(std::string, std::string, double)’ previously defined here
11 | Car(string initMake, string initModel, double initPrice){};
| ^~~
I felt like I've been following the examples given during lectures and textbook activities very closely so I'm lost on how to troubleshoot.
CodePudding user response:
Car(){};
Car(string userMake, string userModel, double userPrice){};
These are defining the constructor bodies, not just declaring their signatures. Since it looks like you want to implement the constructors outside of the class in a .cpp
file (which is good practice to do), just remove the braces. A prototype doesn't have a function body, even an empty one.
Car();
Car(string userMake, string userModel, double userPrice);