2

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

EdChum
  • 376,765
  • 198
  • 813
  • 562
MEMS
  • 617
  • 1
  • 6
  • 11
  • 2
    case 2 is [most vexing parse](http://stackoverflow.com/questions/1424510/most-vexing-parse-why-doesnt-a-a-work), you declared a function that returns `A` – EdChum Dec 09 '16 at 11:21
  • You are talking about a private (actually, protected in your code) **destructor**, not _deconstructor_ – Gian Paolo Dec 09 '16 at 12:05
  • @GianPaolo I've updated the title to fix this – EdChum Dec 09 '16 at 12:07

1 Answers1

2

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

Community
  • 1
  • 1
EdChum
  • 376,765
  • 198
  • 813
  • 562
  • 1
    @MEMS because `main()` needs to call `A::~A()` to unwind the stack, but it can't, because it is protected. In almost all cases you don't want to make the destructor anything but public. – Joseph Ireland Dec 09 '16 at 11:32