0

I'm getting a fatal linking error in the code below, it says:

]+0x10)||undefined reference to `base<node>::pass_derived(node)'|

I wanted to define a base class which has a pointer called poly_type and the base class can also "access" from within itself another class called derived. The problem I run into is line poly_type->pass_derived(n); where the compiler doesn't want to see the derived class where I tried to pass an object of type node. I'm guessing this is a limitation of C++, if so let me know. Heres the broken code,

edit seems like this has been asked somewhere else, I updated the source to reflect that opinion.

pandoragami
  • 5,387
  • 15
  • 68
  • 116
  • possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – jrok Aug 02 '13 at 08:29
  • The definition of `base`'s member function `pass_derived` is missing. – jrok Aug 02 '13 at 08:30
  • creating object of derived class in it's base class is certainly wrong – BЈовић Aug 02 '13 at 08:30

2 Answers2

1

There is no definition of pass_derived in the base class. You declare it as a virtual function but only define it in the derived class. Because it instantiates base in the main function, the compiler tries to generate code for base but it does not find a definition for pass_derived.

You could add a default implementation - even if it is just empty.

As for whether you can eventually get it to call derived::pass_derived instead... :) good luck, it looks like fun. You are building your own version of inheritance?

Graham Griffiths
  • 2,196
  • 1
  • 12
  • 15
  • "You could add a default implementation - even if it is just empty." Yup I just added an empty `virtual void pass_derived(T data) { }` inside `base` class. – pandoragami Aug 02 '13 at 08:35
1

The issue is here:

template < class T>
class base
{
    // ...
    virtual void pass_derived(T data);
};

You declared pass_derived as virtual but not pure virtual. Therefore, the linker raises an error if you don't provide an implementation.

Either you provide an implementation or (which I believe is your intent) you declare it pure virtual:

    virtual void pass_derived(T data) = 0;

but then you cannot instantiate base<T> and must work only with pointers or references to base (which actually point/refer to derived).

Cassio Neri
  • 19,583
  • 7
  • 46
  • 68
  • Yes I tried using `virtual void pass_derived(T data) = 0;` but then it complains about `base b1(1); base b0(0);`? – pandoragami Aug 02 '13 at 08:34
  • "but then you cannot instantiate base and must work only with pointers or references to base (which actually point/refer to derived)." I tried what Graham Griffiths said it works now! – pandoragami Aug 02 '13 at 08:37
  • @lost_with_coding: I've updated the answer to say exactly that. – Cassio Neri Aug 02 '13 at 08:38