Pure virtual destructor of a local abstract class
Asked Answered
F

3

5

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?

Fluorocarbon answered 1/2, 2017 at 10:34 Comment(2)
All method definitions of local class should be inlined inside the class.Bremerhaven
As you are in local scope (so you control the dependencies), you may get rid of = 0 and provide code directly.Bremerhaven
B
6

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

Backwards answered 1/2, 2017 at 10:45 Comment(0)
D
4

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.

Dieback answered 1/2, 2017 at 10:48 Comment(0)
C
1

In C++ you cannot have nested functions. By doing

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

IMO, for nested class with a function, we have to define all non-pure functions in the class block.

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

Chabot answered 1/2, 2017 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.