Prasath Shanmugakani
Prasath Shanmugakani

Reputation: 129

Dynamic casting pointer to Reference and reference to pointer

I am new to CPP and trying to learn dynamic casting . Unfortunately, am getting the below error

main.cpp: In function 'void PRINT(A&)':
main.cpp:30:40: error: cannot dynamic_cast 'Ref_A' (of type 'class A') to type 'class B*' (source is not a pointer) B *Ref_PTR = dynamic_cast<B*>(Ref_A);

If some one can teach me, what is going on ?

Can we cast reference to pointer or pointer to reference ? Can we cast only Base reference to Derived reference ? Can we cast only Base pointer to derived pointer ?

========================================================================

#include <iostream>
#include <exception>
#include <typeinfo>

using namespace std;

class A {
public:
  virtual void dummy() {cout<< "Am in Base Class \n"; }
};

class B : public A {
public:
  virtual void dummy() {cout<< "Am in first Derived Class \n"; }
};

class C : public B {
public:
  virtual void dummy() {cout<< "Am in second Derived Class \n"; }
};

void PRINT(A &);

int  main()
{
   B b;
   C c;
   PRINT(b);
   PRINT(c);
   return 0;
}

void PRINT(A &Ref_A )
{
    try
    {
        B &Ref = dynamic_cast<B&>(Ref_A);
        Ref.dummy();
    }
    catch(std::bad_cast exp) { std::cout<<"Caught bad cast in the Second catch \n"; }

    B *Ref_PTR = dynamic_cast<B*>(Ref_A);
    if (Ref_PTR)
     Ref_PTR->dummy();
    //Ref_A.dummy();
}

Upvotes: 2

Views: 2736

Answers (3)

Joseph D.
Joseph D.

Reputation: 12174

From expr.dynamic.cast#1

The result of the expression dynamic_­cast<T>(v) is the result of converting the expression v to type T. T shall be a pointer or reference to a complete class type, or “pointer to cv void”

In your code void PRINT(A &Ref_A ),

B &Ref = dynamic_cast<B&>(Ref_A);

Ref_A is a reference and you want to cast it to a reference B&. This will result to bad_­cast as per expr.dynamic.cast#9

Do this instead:

B *b = dynamic_cast<B*>(&Ref_A); // cast to B*

Upvotes: 2

Arkady Godlin
Arkady Godlin

Reputation: 588

you could do this.

B *Ref_PTR = dynamic_cast<B*>(&Ref_A);

but this is very ill, your class define dummy() as virtual so you should not cast from base class to derived class without very good justification.

you could use just Ref_A.dummy(); and it will call the correct implementation

Upvotes: 1

Can we cast reference to pointer or pointer to reference ?

Nope. A reference and a pointer are different beasts in the C++ type ecosystem.

Can we cast only Base reference to Derived reference ? Can we cast only Base pointer to derived pointer ?

Generally yes. We cast references to references or pointers to pointers. But that's not to say we can't obtain a pointer from a reference. That's what the address-of operator is for:

B *Ref_PTR = dynamic_cast<B*>( &Ref_A );

Upvotes: 4

Related Questions