Reputation: 4118
I've the following C++ snippet:
#include <iostream>
using namespace std;
class A
{
public:
virtual ~A()
{
}
};
A::~A()
{
}
int main(int argc, char * argv [])
{
return 0;
}
Why am I getting these errors?:
error: redefinition of 'A::~A()' A::~A()
error: 'virtual A::~A()' previously defined here
virtual ~A()**
Upvotes: 3
Views: 1972
Reputation: 43662
There's a difference between declaration and definition. C++ follows the ODR - One Definition Rule, that is: you need to define stuff only ONCE.
Declaration = you let the world know something exists and how the parameters/return types are
Definition = you write the actual code for that function/class/object/whatever
In your code you have TWO definitions and one declaration. That violates the ODR:
#include <iostream>
using namespace std;
class A
{
public:
virtual ~A() < - declares a virtual destructor
{ <- defines the code (nothing) for the virtual destructor
}
};
A::~A() <- defines the code AGAIN for the virtual destructor of the class A
{
}
int main(int argc, char * argv [])
{
return 0;
}
This is not allowed and thus the error. If the defines were:
#include <iostream>
using namespace std;
class A
{
public:
virtual ~A()
{
printf("World?");
}
};
A::~A()
{
printf("Hello?");
}
The compiler wouldn't know if you wanted to print "Hello?" or "World?".
The virtual keyword doesn't help here since it only says: "if a class derives from this one and has a destructor, use polymorphism". It's out-of-topic talking about polymorphism here so I'll let it go.
Upvotes: 3
Reputation: 310950
This is a definition of the destructor inside the class definition
class A
{
public:
virtual ~A()
{
}
};
and this is also the destructor definition outside the class definition.
A::~A()
{
}
So you defined the destructor twice and the compiler reports about this mistake.
You could define the destructor inside the class the following way
class A
{
public:
virtual ~A() = default;
};
Upvotes: 1
Reputation: 21351
Simply use the following in your class
virtual ~A();
instead of
virtual ~A()
{
}
The compiler is actually telling you exactly what the problem is here. You have two implementations - one inline in your class and another outside it here
A::~A()
{
}
you cannot have both.
Upvotes: 6
Reputation: 20993
You are defining the destructor twice - once inline in the class, once outside. You need e.g. to change the inline definition to declaration only:
virtual ~A();
Upvotes: 1