Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: error LNK: unresolved external symbol, resulting from virtual functions

Overview of classes etc of my interface!

Animal.H:

class Animal
{
public:
   virtual void walk();
}

Animals.CPP

=EMPTY

Cow.H:

class Cow : public Animal
{
public:
   virtual void walk();
}

Here it should outomatically know the function walk is taken from the class where it's derived from right? (e.a. Animal..) when i wouldnt define the function walk, it should say i should define it right...?

Cow.CPP:

void Cow::walk()
{
   //do something specific for cow
}

SomeOtherClass.H

namespace SomeNamespace
{
   void LetAnimalWalk();
}

SomeOtherClass.CPP

Cow myCow;
namespace SomeNamespace
{
   void LetAnimalWalk()
   {
      myCow.walk();
   }
}

This should work right?... i mean, the namespace, the "Class::..." things? and the way i inherit and use the interface?

Because this way i get with EVERY FUNCTION i made from the interface, so every virtual function gives me the following error:

SomeOtherClass.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall Cow::Walk (...etc etc...) referenced in function "void __cdecl SomeNamespace::LetAnimalWalk() (...etc etc...)

Does anyone know what i'm doing wrong, what i do find mostly is that it means i've not declared a function right (somewhere in Cow.cpp??)

Thanks in advance guys

like image 670
Sebastiaan van Dorst Avatar asked Mar 07 '13 14:03

Sebastiaan van Dorst


4 Answers

class Animal
{
public:
   virtual void walk();
}

You need to define that function or make it pure virtual like

class Animal
{
public:
   virtual void walk() = 0;
}
like image 138
Barış Uşaklı Avatar answered Oct 22 '22 12:10

Barış Uşaklı


When you have a virtual function that you don't want to define in the base class, you need to make it abstract, this is done using the following syntax:

class Animal
{
public:
   virtual void walk() = 0;
}

Without this you will get an error if it is not defined, and with this you will get an error if any derived class does not define it.

like image 41
Jack Aidley Avatar answered Oct 22 '22 12:10

Jack Aidley


either make the function in the base class pure virtual:

class Animal
{
    public:
        virtual void walk() = 0;
}

or define a trivial implementation:

void Animal::walk()
{
   return;    // could also throw an exception here
}
like image 44
jerry Avatar answered Oct 22 '22 14:10

jerry


Animal* animal = new Cow(); animal->walk();

Cow myCow does NOT work obviously!

like image 1
Sebastiaan van Dorst Avatar answered Oct 22 '22 12:10

Sebastiaan van Dorst