Friday, 9 September 2016

Undefined reference to vtable (C++)





I am making an Entity class for my sfml game but I can't understand why the following code can't compile. I get an undefined reference to vtable in Entity error.



Here is the header file:



#ifndef ENTITY_H

#define ENTITY_H
#include
#include
#include
#include

class Entity
{
public:
Entity(std::string id, sf::Vector2f position, float rotation );

virtual ~Entity() = 0;
virtual sf::FloatRect getBoundingRect() const;
virtual float getRadius() const;
void UpdateVelocity(sf::Time);
void UpdatePosition(sf::Time);
void Update(sf::Time);
float getRotation() const;
sf::Vector2f getPosition() const;
sf::Vector2f getVelocity() const;
sf::Vector2f getAcceleration() const;



private:
std::string mId;
sf::Vector2f mPosition;
float mRotation;
sf::Vector2f mVelocity;
sf::Vector2f mAcceleration;
};


#endif // ENTITY_H


and here is the cpp file:



#include "../include/Entity.h"

Entity::Entity(std::string id, sf::Vector2f position, float rotation)
: mId(id)
, mPosition(position)

, mRotation(rotation)
{
}

Entity::~Entity()
{
}


void Entity::UpdateVelocity(sf::Time dt)

{
mVelocity += mAcceleration;
}

void Entity::UpdatePosition(sf::Time dt)
{
mPosition += mVelocity;
}

void Entity::Update(sf::Time dt)

{
UpdateVelocity(dt);
UpdatePosition(dt);
}

float Entity::getRotation() const
{
return mRotation;
}


sf::Vector2f Entity::getPosition() const
{
return mPosition;
}

sf::Vector2f Entity::getVelocity() const
{
return mVelocity;
}


sf::Vector2f Entity::getAcceleration() const
{
return mAcceleration;
}


Any help is much appreciated!


Answer



You are missing the implementation of some virtual methods:




    virtual sf::FloatRect getBoundingRect() const;
virtual float getRadius() const;


If you don't want your Entity class to implement these, declare them as pure virtual:



    virtual sf::FloatRect getBoundingRect() const = 0;
virtual float getRadius() const = 0;



Note that, as commented by @JoachimIsaksson, it isn't completely obvious whether you need your destructor to be pure virtual. You have provided an empty implementation for it, but you still require derived types to implement it. It may be worth considering whether you need it to be pure virtual.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...