Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual destructor of a local abstract class

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?

like image 639
MEMS Avatar asked Dec 19 '22 10:12

MEMS


2 Answers

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

like image 139
A.S.H Avatar answered Dec 24 '22 02:12

A.S.H


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.

like image 40
Smeeheey Avatar answered Dec 24 '22 01:12

Smeeheey