MEMS
MEMS

Reputation: 647

Protected destructor and object initialisation

see the following code :

struct A
{
protected:
    ~A() {};
};
void main()
{
    //case 1:
    A a;
    //error C2248: 'A::~A': cannot access protected member declared in class 'A'

    //case 2:
    A b();//works fine
}

why do I get error in case-1 but not in case-2? many thanks

Upvotes: 3

Views: 169

Answers (1)

EdChum
EdChum

Reputation: 394041

case 1 occurs because you declared the destructor as protected so when you locally declared the object, your program can't access the destructor which is needed to destroy the object.

If you declared a derived object then the derived object would have access to the base class's destructor:

struct B : public A
{}

then in your main you had B b; instead of A a; then it would compile without error.

For case 2 is most vexing parse:

A b();

is a function declaration, it's not doing what you think which is to create an instance of A

Upvotes: 3

Related Questions