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();
}

works great. but now consider the second code, where we need to declare our classes locally inside the 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();  
}

code dose does not compile! Any ideas? is any way to override a pure virtual base class destructor that is declared locally?

+4
source share
3 answers

cppreference says

A class declaration can appear (...) also inside the function body, in which case it defines a local class

...

Member functions of a local class must be fully defined inside the class body

+6
source

, . , : ? , , , . , , , . , : , . , , , , - (.. ) , .

+4

++ .

foo(){
//...
A::~A{} // you define a nested function which is not allowed
//...
}

IMO, for a nested class with a function, we must define all unclean functions in the class block.

If you want your class A to be abstract, you can declare A :: foo () as pure virtual or some new empty functions. In any case, you need to define a virtual dtor outside or inside the class of the class, as this will not lead to a communication error.

+1
source

Source: https://habr.com/ru/post/1668501/


All Articles