'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
Solution 1:[1]
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;
}
Solution 2:[2]
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.
Solution 3:[3]
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
}
Solution 4:[4]
Animal* animal = new Cow(); animal->walk();
Cow myCow does NOT work obviously!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jack Aidley |
| Solution 3 | jerry |
| Solution 4 | Sebastiaan van Dorst |
