0

Given following classes:

// myClass.hpp
class Child1;
class Child2;

class MyClass {
  public:
    virtual void doSomething (const MyClass&) const = 0;
    virtual void doSomething (const Child1&) const = 0;
    virtual void doSomething (const Child2&) const = 0;
};

// child1.hpp
#include "myClass.hpp"

class Child1 : public MyClass {
  public:
    virtual void doSomething (const MyClass&) const override;
    virtual void doSomething (const Child1&) const override;
    virtual void doSomething (const Child2&) const override;
};


// child2.hpp
#include "myClass.hpp"

class Child2 : public MyClass {
  public:
    virtual void doSomething (const MyClass&) const override;
    virtual void doSomething (const Child1&) const override;
    virtual void doSomething (const Child2&) const override;
};

The compiler gives me the errors:

undefined reference to 'Child1::doSomething(MyClass const&)'

The same error is printed for the other doSomething(..) functions.

I'm sure there is some mistake in including files (I use include guards for every header-file!!). My questions are: Where do I have to include the corresponding files and where do I need forward declaration?

Kapa11
  • 311
  • 2
  • 18
  • Please check your cpp files, and if they are even compiled, add more code to allow us to see full picture of what you have. – Denis Ermolin Dec 12 '16 at 08:08

2 Answers2

1

"Undefined reference" looks like a linker problem. Ensure that you have a child1.cpp including child1.hpp and that you compile and with it; and that child1.cpp define the override function in the correct way.

Hans Olsson
  • 11,123
  • 15
  • 38
1

The error tells you that there is no reference to the whole Method.

In other words you need to define the Method in a *.cpp File or directly in the header. See for example this overview or this similar question. The answers tell you that is actual not a Compiler error but a Linker error.

Edit: As Hans Olsson Answer suggests, it could also be that you need to include your cpp files.

If you do not exactly know how the implementation will look like but want to know if you header-concept works you can implement them empty

virtual void doSomething (const MyClass&) const override {}

Or compiler your code with gcc with the flag "-c" which tells gcc enter to just do the compiling not the linking.

Community
  • 1
  • 1
ab.o2c
  • 238
  • 2
  • 7
  • You're both right. Actually, it was a problem in linking instead of compiling. From now on, I'm a big fan of the "-c" compiler flag :) – Kapa11 Dec 12 '16 at 08:40
  • But be aware that it is no "eierlegende wollmilchsau" (dont know how to translate that) – ab.o2c Dec 12 '16 at 09:01