0

I get 'error LNK2001: unresolved external symbol' when I comment in my constructor in my derived class.

My base class defines a virtual OnEnter and OnExit, my derived class implements those functions, all is good. Then when I add a constructor to my derived class it wont compile.

1>State.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall State::OnEnter(void)" (?OnEnter@State@@UAEXXZ)
1>State.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall State::OnExit(void)" (?OnExit@State@@UAEXXZ)

State is my base class.

//State.h
#ifndef STATE_H
#define STATE_H

class State
{
public:
    virtual void OnEnter();
    virtual void OnExit();
};

#endif

//State.cpp
#include "State.h"


//DateEntryView.h
#ifndef DATE_ENTRY_VIEW_H
#define DATE_ENTRY_VIEW_H

#include "State.h"

class DateEntryView
    : public State
{
public:
    DateEntryView();
public:
    void OnEnter();
    void OnExit();
};

#endif

//DateEntryView.cpp
#include "DateEntryView.h"

DateEntryView::DateEntryView()
{

}

void DateEntryView::OnEnter()
{

}

void DateEntryView::OnExit()
{

}
Josh Braun
  • 490
  • 2
  • 16

2 Answers2

0

You have to make your OnEnter and OnExit methods pure virtual in your state class.

like this

class State
{
public:
  virtual void OnEnter() = 0;
  virtual void OnLeave() = 0;
};

class StateOne : public virtual State
{

public:

  StateOne()
  {
  }

  virtual void OnEnter()
  {
  }

  virtual void OnLeave()
  {
  }

};


int main()
{
  State *state = new StateOne;
  state->OnEnter();
  state->OnLeave();
  delete state;

  return 0;
}

Or if you don't want them pure virtual add braces

class State
{
public:
  virtual void OnEnter()
  {
  }
  virtual void OnLeave()
  {
  }
};
user743414
  • 936
  • 10
  • 23
  • 1
    if you implement them in the base class, you don't need do that. – Matt Apr 10 '14 at 12:33
  • Depends on the request abstract base class vs non abstract base class – user743414 Apr 10 '14 at 12:36
  • i don't know why they down voted your post but i did want to make them pure virtual thanks – user3345413 Apr 10 '14 at 12:36
  • Its strange because it built with another compiler and worked for another set of derived classes. So weird. I think its because those objects were not being instantiated had code commented out etc. – user3345413 Apr 10 '14 at 12:37
0

You have not provided an implementation for OnEnter or OnExit in the source you have supplied.

If they are supposed to have implementations, then you presumably have a state.c file which, when you compile, produces a state.o file. When you produce your executable you need to include this file in the linking stage.

If they are not supposed to have implementations, eg. if it is an abstract base class, then you need to declare them like this:

virtual void OnEnter() = 0;
virtual void OnExit() = 0;
harmic
  • 28,606
  • 5
  • 67
  • 91