#Basic Animal Inheritence Example

29 messages · Page 1 of 1 (latest)

safe rapids
#

I'm trying to make a Animal class hierarchy but I'm getting this error: undefined reference to `vtable for animals::Chicken'

Here is the code:
animals.h

namespace animals {

class Animal {

public:
  virtual void make_noise() = 0;
  virtual void eat() = 0;
  virtual ~Animal() {}
};

class Chicken : public Animal {

  int age;
  bool rooster;

public:
  Chicken() : age(0), rooster(false) {}
  ~Chicken() override {}

  void make_noise() override;

  void eat() override;
};

} // namespace animals

animals.cpp

#include "animals.h"
#include <iostream>

void animals::Animal::make_noise() { std::cout << "be caw!" << '\n'; }
void animals::Animal::eat() { std::cout << "peck... peck.." << '\n'; }

and main.cpp

#include "animals.h"
#include <iostream>

int main() {

  std::cout << "Welcome to C++" << '\n';

  animals::Animal *an = new animals::Chicken();

  an->make_noise();

  return 0;
}
peak blazeBOT
#

When your question is answered use !solved or the button below to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

safe rapids
#

CMakeLists.txt ```cmake

...

project(app)

add_executable(app src/main.cpp src/animals.h src/animals.cpp)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address --pedantic")

...

fresh marten
#

you probably meant to write animals::Chicken::make_noise() instead of animals::Animal::make_noise(), and same for eat

safe rapids
#

wow...

#

yes I did lol

#

thanks

long mantle
#

wait, does that not generate a compiler error?

fresh marten
#

np, stuff like that happens

#

you can provide an implementation for a pure virtual member function

proper mauve
viral forge
#

virtual void make_noise() = 0; and is also defined?

#

how is that a thing

long mantle
proper mauve
proper mauve
#

just special ones

long mantle
fresh marten
proper mauve
#

or just declare it locally here

#

no need to allocate

safe rapids
viral forge
long mantle
#

yes

viral forge
#

so how are you going to call any Animal member function if you can not instantiate an Animal?

long mantle
#

you can call it from a derived class or another memeber function of Animal

viral forge
#

ah directly on the derived

peak blazeBOT
#

@safe rapids Has your question been resolved? If so, type !solved :)

safe rapids
#

!solved