-3
#include<iostream>

class base{
  public:
  virtual void run()=0;
  protected:
  ~base();
};

class derived : public base {
   public:
   void run(){};
   ~derived();
};

int main(){
  std::shared_ptr<base> b;
  b.reset(new derived);
  b->run();
}

I have an abstract base class and derived class from it. In main, I define a shared pointer and allocate it with derived type. Then, I use the virtual function. If I comment out b.reset(new derived) then it works fine. The error message is

Undefined symbols for architecture x86_64: "derived::~derived()", referenced from: std::__1::shared_ptr::shared_ptr(derived*) in test-274b97.o std::__1::__shared_ptr_pointer, std::__1::allocator >::__on_zero_shared() in test-274b97.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any answer will be appreciated!
Thanks.

Celeo
  • 5,583
  • 8
  • 39
  • 41

1 Answers1

3

You did not define destructors for classes base and derived. You only declared them. Also the destructor has to be virtual

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Destructor doesn't have to be virtual in his specific case, though it's a good idea in general. – Mooing Duck Nov 04 '14 at 17:35
  • @MooingDuck: No, it must be virtual in `base` in this case because there is polymorphic deletion (`shared_ptr`). – Fred Larson Nov 04 '14 at 17:36
  • 2
    @FredLarson: Setting the value of a `shared_ptr` via `reset` stores the type given, in this case a `derived*`. There is no polymorphic deletion here. If it were `unique_ptr` you'd be right, but `shared_ptr` is magic. http://en.cppreference.com/w/cpp/memory/shared_ptr/reset "Proper delete expression corresponding to the supplied type is always selected, this is the reason why the function is implemented as template using a separate parameter Y." – Mooing Duck Nov 04 '14 at 17:39
  • @MooingDuck: Oh wow, I didn't know that. Still gives me the heebie jeebies if the destructor isn't virtual, though. – Fred Larson Nov 04 '14 at 17:41