Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting pointer from one base type to another

Tags:

c++

pointers

-EDIT-

Thanks for the quick response, I'd been having really weird problems with my code and I changed my casts to dynamic_cast and its working perfectly now

-ORIGINAL POST-

Is it safe to cast a pointer of one base class to another base class? To expand on this a bit, will the pointer I've marked in the following code not result in any undefined behavior?

class Base1
{
public:
   // Functions Here
};


class Base2
{
public:
   // Some other Functions here
};

class Derived: public Base1, public Base2
{
public:
  // Functions
};

int main()
{
  Base1* pointer1 = new Derived();
  Base2* pointer2 = (Base2*)pointer1; // Will using this pointer result in any undefined behavior?
  return 1;
}
like image 984
Raphael Avatar asked Jul 16 '12 16:07

Raphael


People also ask

How do I cast one pointer to another?

reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different. It does not check if the pointer type and data pointed by the pointer is same or not.

Can you convert a pointer from a derived class to its base class?

A pointer to the derived class can be converted to a pointer to the base class. If this is the case, the base class is said to be accessible.

Can a pointer point to another class 1 point?

It is true that a pointer of one class can point to other class, but classes must be a base and derived class, then it is possible. To access the variable of the base class, base class pointer will be used.

Can you cast from base class to derived?

When we create an instance of a base class, its data members are allocated in memory, but of course data members of inherited classes are not allocated. So, downcasting from a base to a derived class is not possible because data members of the inherited class are not allocated.


2 Answers

Will using this pointer result in any undefined behavior?

Yes. The C-style cast will only try the following casts:

  • const_cast
  • static_cast
  • static_cast, then const_cast
  • reinterpret_cast
  • reinterpret_cast, then const_cast

It will use reinterpret_cast and do the wrong thing.

If Base2 is polymorphic, i.e, has virtual functions, the correct cast here is dynamic_cast.

Base2* pointer2 = dynamic_cast<Base2*>(pointer1);

If it doesn't have virtual functions, you can't do this cast directly, and need to cast down to Derived first.

Base2* pointer2 = static_cast<Derived*>(pointer1);
like image 68
R. Martinho Fernandes Avatar answered Oct 15 '22 15:10

R. Martinho Fernandes


You should use dynamic_cast operator. This function returns null if types are incompatible.

like image 27
flamingo Avatar answered Oct 15 '22 16:10

flamingo