C++ symbol referencing error
I've been trying to find what the problem is to this following code part. I've written a custom exception class where I have a base class for stack errors, and then some classes deriving from it one of them called stack_full_error
.
I have some problem compiling it though, I get the following error.
Undefined fi开发者_如何学运维rst referenced
symbol in file
stack_error::~stack_error() /var/tmp//ccFwZ5Kd.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
It says something about the destructor, and I have been trying some things to fix it, with no success. Anyway I hope someone can tell me what the problem is.
class stack_error : public exception
{
public:
stack_error(string const& m) throw()
: exception(), msg(m) {};
virtual ~stack_error() throw() =0;
virtual const char* what() const throw()
{
return msg.c_str();
}
private:
string msg;
};
class stack_full_error : public stack_error
{
public:
stack_full_error() throw()
: stack_error("Exception: stack full") {};
~stack_full_error() throw() {};
};
And here where I call the exception for this first time
template <class T>
void Stack<T>::push(T i)
{
if(is_full())
throw stack_full_error();
this->first = new Node<T>(this->first, i);
amount++;
}
Pure virtual or not, stack_error
must define its destructor because it is implicitly called from stack_full_error
destructor. You should add :
stack_error::~stack_error() {}
in an implementation file.
You cannot have an abstract destructor. You need to define it in stack_error
. (see the correction below)
Did you mean to make in virtual?
Unlike other virtual functions, virtual destructors are not overriding each other. The destructors of all the base classes will be executed sequentially (starting from the most derived class destructor). Each class musty have a destructor; even if you don't define a destructor, it's created implicitly.
Correction:
You can make the destructor abstract, but need to define its body anyway. Like that:
virtual ~stack_error() = 0 {};
if this your compiler the latest C++0x features. Otherwise you have to define the body outside:
class stack_error
{
...
virtual ~stack_error() = 0;
...
};
stack_error::~stack_error() {}
Abstract (=0
) means that it needs to be defines in the derived classes; nevertheless you have to define the destructor's body.
I am not sure destructors can (should?) be abstract. Destructors should be virtual but I seem to remember having issues when they where abstract.
精彩评论