consider the following code :
struct A {
virtual void foo() {}
virtual ~A() = 0;
};
struct B :public A
{
virtual void foo() {};
};
A::~A() {};
int main()
{
A * a = new B();
a->foo();
}
it works perfectly fine. but now consider the second code where we need to declare our classes locally inside a function as:
void foo()
{
struct A {
virtual void foo() {}
virtual ~A() = 0;
};
struct B :public A
{
virtual void foo() {};
};
A::~A() {}; //error C2352 : 'A::~A' : illegal call of non - static member function
A * a = new B();
a->foo();
}
int main()
{
foo();
}
the code dose not compile! any idea? is the any way to redefine the pure virtual destructor of the base class which is declared locally?
cppreference says
A class declaration can appear (...) and inside the body of a function, in which case it defines a local class
...
Member functions of a local class have to be defined entirely inside the class body
There is no way to do what you want. But also, consider this: why would you normally want to give a body definition for a pure virtual destructor? The typical answer is that you want to make the class abstract but have no other methods which can be made pure virtual. The scenario in which this arises is typically where you have no direct control over the use or inheritance from of your class. But this can never happen for a class defined locally inside a function: any use thereof by definition has to be within exactly the same function body, giving the author full control over usage. So for example you can make sure your class is always inherited from rather than used as-is (i.e. the purpose of forcing a class to be abstract) simply by observing this rule yourself within the directly-controlled context of the local function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With