65.9K
CodeProject is changing. Read more.
Home

BUG in Visual C++ access for destructors with virtual base classes

starIconstarIconemptyStarIconemptyStarIconemptyStarIcon

2.00/5 (1 vote)

Apr 6, 2000

viewsIcon

62921

downloadIcon

1

When inheriting from a virtual base class the access specifier for the destructor is ignored

Introduction

This bug appears in VC6 SP3, and possibly earlier versions as well.

When inheriting from a virtual base class the access specifier for the destructor is ignored

To demonstrate, if the word virtual is commented out as shown below in the declaration of class B, this program correctly produces the error message

 xxx.cpp(28) : error C2248: 'B::~B' : cannot
 access protected member declared in class 'B'
 xxx.cpp(23) : see declaration of 'B::~B'

If the word virtual is un-commented then the program builds without error messages despite the destructor being declared private

The offending code

#include "stdafx.h"

class A {
protected:
    ~A() {}
};

class B : virtual public A {
private:
    ~B() {}
};

int main(int argc, char* argv[])
{
    B b;
    return 0;
}

As a bit of history, I am implementing some smart pointers and want to ensure that the smart-pointer target object cannot be created locally on the stack, nor do I want to be able to explicitly call delete on a pointer to such an object. Hence I want the destructor to be private. However, this fails (as shown above) when I am inheriting from a virtual base class.