Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overloaded Constructor Throwing Redefinition Error

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading