ryskajakub
ryskajakub

Reputation: 6431

undefined reference

i have these classes (and function):

template <class A>
class Factory{
  public:
    A (*binOp(void))(A,A);
};
int sum(int a, int b){
  return a + b;
}
class IntFactory : public Factory<int>{
  public:
    int (*binOp(void))(int,int){
      return &sum;
    }
};
template <class A>
class SpecializedList{
  protected:
    List<A>* list;
    Factory<A>* factory;
  public:
    SpecializedList(List<A>* list,Factory<A>* factory){
      this -> list = list;
      this -> factory = factory;
    }
    A sum(){
      return (list -> foldLeft(factory -> zero(), factory -> binOp()));
    }
};

// in main
SpecializedList<int>* sl = new SpecializedList<int>(join1 -> getList(),new IntFactory());
cout << sl -> sum() << endl;

I get errors:

/tmp/ccxdiwUF.o: In function SpecializedList<int>::sum()':
list.cpp:(.text._ZN15SpecializedListIiE3sumEv[SpecializedList<int>::sum()]+0x19): undefined reference toFactory::binOp()'
list.cpp:(.text._ZN15SpecializedListIiE3sumEv[SpecializedList::sum()]+0x2c):  `Factory::zero()'
collect2: ld returned 1 exit status
Do anybody know why? I was googling relevant part of the error messages, and it looked like it's related to problems, when one has the code scattered in different files. I have everything in single file for now.

Upvotes: 2

Views: 547

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361722

Two problems:

  • Factory doesn't define the function binOp().
  • Factory doesn't even have the function zero().

Solution:

  • Make the function binOp() a pure virtual function in Factory by specifying the pure-specifier as:

     virtual A (*binOp(void))(A,A) = 0; //"=0" is called pure-specifier
    //^^^^^^ this makes the function virtual
    

    No need to define it now (as far as linker-error is concerned). Optionally, you can define it as well.

  • Declare a function zero() in Factory. If you don't make it pure virtual, then must define it.

Upvotes: 6

Related Questions