In C++ primer(5th) 19.2.1 about dynamic_cast. It says, for dynamic_cast<type*>(e)
to be successful,
the type of e must be either a class type that is publicly derived from the target type, a public base class of the target type, or the same as the target type
However, for the following code:
class B{
public:
virtual ~B(){}
};
class D : public B{};
B *pb = new B;
D *pd = dynamic_cast<D*>(pb);
if(pd == 0) cout << "err" << endl;
The output is "err". But the type of pb is a public base class of type D.
Is this a mistake in C++ primer(5th)? Or do I just misunderstand these words?
pb
has to point to aD
to begin with. You have aB
. – StoryTeller - Unslander Monicapb
has typeB*
, it cannot point at anything other than aB
. – Kerrek SBD
is-aB
however :P – StoryTeller - Unslander Monica