I have written a code which uses dynamic_cast
operator for casting the base class pointer which points the derived class object. But I have a doubt regarding the casting process. First have a look at the source code and the output.
CODE
#include <iostream>
using namespace std;
class Base
{
public:
virtual void BasePrint(void)
{
cout << "This is base print\n";
}
};
class Derived1 : public Base
{
public:
void Derived1print(void)
{
cout << "This is derived1 print\n";
}
};
class Derived2 : public Base
{
public:
void Derived2print(void)
{
cout << "This is derived2 print\n";
}
};
int main(void)
{
Base *ptr = new Derived1;
Derived1 *caster1 = dynamic_cast<Derived1 *>(ptr);
if (caster1 != NULL)
caster1->Derived1print();
Derived2 *caster2 = dynamic_cast<Derived2 *>(ptr);
if (caster2 == NULL) // Doubt in this line
caster2->Derived2print();
return 0;
}
OUTPUT
This is derived1 print
This is derived2 print
As in line number 40 it is written that if (caster2 == NULL)
then only run this line caster2->Derived2print();
and the output is visible in the terminal!
Now if the caster2
pointer is NULL
then how it can be dereferenced using the arrow operator ->
to show the output of the Derived2print()
method?