简体   繁体   中英

undefined reference, compilation error

I am trying to use class inheritance. I have taken a code from a book and tweaked it a bit to create Class Mammal and a Class Dog which inherits Mammal member data. The code is:

#include<iostream>

enum BREED{Labrador,Alcetian,Bull,Dalmetian,Pomerarian};


class Mammal{

 public:
    Mammal();
    ~Mammal(){}
    double getAge(){return age;}
    void setAge(int newAge){age=newAge;}
    double getWeight(){return weight;}
    void setWeight(double newWeight){weight=newWeight;}
    void speak(){std::cout<<"Mammal sound!\n";}
 protected:
    int age;
    double weight;

};

class Dog : public Mammal{

 public:
    Dog();
    ~Dog(){}
    void setBreed(BREED newType){type=newType;}
    BREED getBreed(){return type;}
 private:
    BREED type;
};

int main(){
 Dog Figo;

 Figo.setAge(2);
 Figo.setBreed(Alcetian);
 Figo.setWeight(2.5);
 std::cout<<"Figo is a "<<Figo.getBreed()<<" dog\n";
 std::cout<<"Figo is "<<Figo.getAge()<<" years old\n";
 std::cout<<"Figo's weight is "<<Figo.getWeight()<<" kg\n";
 Figo.speak();

 return 0; 
}

When I run this code,, it gives me the following error:

C:\\cygwin\\tmp\\cc7m2RsP.o:prog3.cpp:(.text+0x16): undefined reference to `Dog::Dog()' collect2.exe: error: ld returned 1 exit status

Any help would be appreciated. Thanks.

You didn't define constructors, you only declared them:

class Mammal{
public:
    Mammal();  // <-- declaration

...

class Dog : public Mammal{
public:
    Dog();  // <-- declaration

When you declare a constructor (or any function) then the C++ compiler will look for the constructor's definition elsewhere. And when it can't find it it complains. For basic definitions try this:

class Mammal{
public:
    Mammal() {};  // <-- definition

...

class Dog : public Mammal{
public:
    Dog() {};  // <-- definition

You can also remove them entirely since they don't seem to do anything (C++ will insert default constructor for you).

This because you have just declared the non-parameterized constructors Dog(); and Mammal(); in respective classes, but not defined it.

To remove the error do following:

  • In class Mammal , change line Mammal(); to Mammal(){} AND
  • In class Dog , change line Dog(); to Dog() {} .

You have declared constructor for the class Dog::Dog(); , its not defined. Means constructor is missing body. Define a constructor as follows

public: Dog::Dog(){ //statements }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM