-3

i get confused in this part while we are using dynamic_cast to get ensure that the conversion result between pointers is valid complete object of the destination type , i can't get what is meaning by valid complete object here is example

#include <iostream>
#include <exception>
using namespace std;

class Base { virtual void dummy() {}


 };
class Derived: public Base {public:
void print(){cout << "NiGHt!\n";
 int a; };

int main () {
try {
Base * pba = new Derived;
Base * pbb = new Base;
Derived * pd;

pd = dynamic_cast<Derived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast.\n";

pd = dynamic_cast<Derived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast.\n";

 } catch (exception& e) {cout << "Exception: " << e.what();}

 return 0;
}

if this two lines indicate that the conversion result succeed so why i can't use pointer pba to get into Derived class ?

pd = dynamic_cast<Derived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast.\n";
  • The second cast would not succeed in real code. – juanchopanza Sep 10 '14 at 07:01
  • [dynamic_cast](http://www.cplusplus.com/doc/tutorial/typecasting) Informally, you could say an object of a complete type, is an object instantiation belonging to a fully defined class. A class may make use of an object with an incomplete type as a member, like [this](http://pastebin.com/nEA9wiDp) – iamOgunyinka Sep 10 '14 at 07:24
  • Fix your indentation – zoska Sep 10 '14 at 08:28

1 Answers1

0

The line pd = dynamic_cast<Derived*>(pba); means that cast the pba pointer (which is a pointer to a Base class, however it contains a Derived object because: Base * pba = new Derived) to a pointer pointing to a Derived object. This cast will fail if there is no relationship between Base and Derived (ie: Derived must be derived from Base) and will return 0.

And why cannot you use pba to get the Derived class? Becuase pba is a pointer to a Base class. So it has no idea that there even is a Derived class.

Reference: When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Community
  • 1
  • 1
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167