dynamic_cast and accessible base classes.
In ?15.4.1, "Dynamic_cast," of Stroustrup's TC++PL (Sp. Ed. 2000, 2nd
printing, p. 408), the author gives the following as an illustration
of the application of dynamic_cast, using:
dynamic_cast<T*>(p);
saying "if p is of type T* or an accessible base class of T, the
result is exactly as if we had simply assigned p to a T*." He then
goes on to give an example where the base class in inaccessible
(protected):
class BB_ival_slider
: public Ival_slider, protected BBslider { /* ... */ };
void f(BB_ival_slider* p) {
// <snip>
BBslider* pbb1 = p; // error: BBslider is a protected base
BBslider* pbb2 = dynamic_cast<BBslider*>(p); // ok: pbb2 = 0
}
However, when I attempt to convert this into a brief working example,
as for instance here...
#include <iostream>
class A {
public:
virtual void do_stuff() = 0;
};
class B : protected A {
public:
void do_stuff() { }
};
int main()
{
B *b = new B();
A *a = dynamic_cast<A *>(b); // line 17
if (!a) {
std::cout << "A *a = 0\n";
}
delete b;
return 0;
}
.... I get errors that suggest that the dynamic cast, in this
instance, is no more allowed than the attempt at direct
assignement is for the compilers that I have access to.
For instance:
Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for
ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing. All rights reserved.
MODE:strict errors C++ noC++0x_extensions
"ComeauTest.c", line 17: error: conversion to inaccessible
base class "A" is not allowed
A *a = dynamic_cast<A *>(b);
^
1 error detected in the compilation of "ComeauTest.c".
and:
gcc 3.4.4
error: `A' is an inaccessible base of `B'
Only VC++, being lax, provides a warning where the others produced an
error...
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version
15.00.30729.01
: warning C4540: dynamic_cast used to convert to inaccessible or
ambiguous base; run-time test will fail ('B *' to 'A *')
The latter, surprisingly, is what I would have expected to be the
case from my understanding of Stroustrup's illustration.
Is it possible that I have "lost something in translation" in
my example above?
Paul Bibbings
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]