简体   繁体   中英

I'm trying to write a class where the child class will inherit the methods from the parent class, but my code won't compile

I am just trying to get my code to compile. I've done this before and it looks exactly the same in its methods, but for some reason, when I'm trying to run it using different methods, it won't compile. The error is in the cpp file. Any help would be great! Thanks

Error is:

/tmp/ccexQEF7.o: In function `Animal::Animal(std::string)':
Animal.cpp:(.text+0x11): undefined reference to `vtable for Animal'
collect2: error: ld returned 1 exit status

This is my header file:

#include <iostream>
#ifndef ANIMAL_H
#define ANIMAL_H

class Animal
{
  
  public:
  
    Animal(std::string name);
    std::string get_name();
    virtual int get_weight();
    virtual int get_age();
    
  protected:
    
    std::string animalName;
    
};

class Cat: public Animal
{
  
  public:
  
    Cat(double weight, int age);
    
    std::string get_name();
    virtual int get_age();
    virtual int get_weight();
    
  protected:
  
    std::string catType;     
};

#endif

This is my cpp file:

#include <iostream>
#include "Animal.h"
using namespace std;

Animal::Animal(string name)
{
    animalName = name;
};

You have either to define in the base class the virtual member function get_weight and get_age explicitly or declare them as pure virtual functions as for example

class Animal
{
  
  public:
  
    Animal(std::string name);
    std::string get_name();
    virtual int get_weight() = 0;
    virtual int get_age() = 0;
    
  protected:
    
    std::string animalName;
    
}

In derived classes you should override them using the specifier override as for example

    int get_weight() override;
    int get_age() override;

and provide their definitions.

Pay attention to that it would be better to declare the member functions as constant functions as for example

class Animal
{
  
  public:
  
    Animal(std::string name);
    std::string get_name();
    virtual int get_weight() const = 0;
    virtual int get_age() const = 0;
    
  protected:
    
    std::string animalName;
    
}

because it seems they do not change objects for which they are called.

You have two undefined virtual methods:

   virtual int get_weight();
   virtual int get_age();

These methods have to be defined so that a vtable (virtual table) can be compiled for a class. At the very least, you need to give them a dummy implementation:

   virtual int get_weight() { return 0; }
   virtual int get_age() { return 0; }

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