Undefined Reference to member function (false unexpected error)

615 views Asked by At

I would like this mov() virtual member function to get() the coordinates x,y
However there is this error which doesn't make sense at all
pirate.o:: In function 'ZN6Pirate3movEPS_PA100_3Sea':|
pirate.cpp:: undefined reference to `Ship::getX() const' (line 7)

getX() is inherited
Parent Class:Ship, Derived class:Pirate

Ship.h

#ifndef SHIP_H
#define SHIP_H
#include <iostream>
#include "sea.h"
#define SIZE 100
class Ship
{
private:
     int x,y; //Coordinates of ship
public:
    Ship(){}
    virtual void func()=0;
    virtual void mov()=0;
protected:
    int getX()const;
    int getY()const;
};

#endif

Ship.cpp

#include "Ship.h"
int Ship::getX()const
{return x;}    
int Ship::getY()const
{return y;}
virtual void func()=0;
virtual void mov()=0;

Pirate.h

#ifndef PIRATE_H
#define PIRATE_H
#include "ship.h"
#include "sea.h"
class Pirate : public Ship
{
protected:
        void func();
        void mov(Pirate * ship , Sea Map[SIZE][SIZE]);
};
#endif

Pirate.cpp

#include "pirate.h"

void Pirate::func(){}

void Pirate::mov(Pirate* ship , Sea Map[SIZE][SIZE])
{
 int x_ref = ship->getX();
 int y_ref = ship->getY();
}

Sea.h

#ifndef SEA_H
#define SEA_H
#include "ship.h"
class Sea
{
private:
    bool hasShip;

public:
    Sea(){hasShip=0;}
    bool gethasShip()const{return hasShip;}
    void sethasShip(bool i){hasShip = i;}
};
#endif
2

There are 2 answers

1
Amadeus On BEST ANSWER

The other answer is exactly right. If you remove those two lines it will compile correctly, and the error you're getting (and the fact that you're not getting other errors) is due to the fact that Ship.cpp is not properly included in the compilation process.

I'm not sure if you have access to Visual Studio 2013, but if you do, I tested it to be sure with the following solution/project: http://filebin.ca/1i9z9TwF2kf5/Pirates.zip

3
Jonathan Wakely On

You forgot to compile and link Ship.cpp

I can tell this because if you'd tried to compile it then you'd have got an error here:

virtual void func()=0;
virtual void mov()=0;

That's not valid C++, you don't define pure virtuals like that (you don't need to define them at all unless they are destructors or you call them explicitly)

If you don't link with the file with the definition of Ship::getX() const then it's not surprising that the linker tells you it's undefined.