Search code examples
c++downcast

Downcasting procedure


Can anyone please explain me if its alright to downcast this way or we SHOULD use an explicit type cast for it?

#include<iostream>

using namespace std;

class base {
public:
    virtual void func() { cout<<"Base \n"; }
            void fun()  { cout<<"fun"; }
};

class derived1 : public base {
public:
            void func() { cout<<"Derived 1\n"; };
            void fun()  { cout<<"fun1"; }
};

class derived2 : public derived1 {
public:
            void func() { cout<<"Derived 2\n"; }
            void fun()  { cout<<"fun2"; }
};


int main()
{
    base * var = new derived1;

    ((base *) var)-> fun();
    ((derived1 *) var)-> fun();
    ((derived2 *) var)-> fun(); 

    // How does this work?
}

Solution

  • ((base *) var)-> fun(); and ((derived1 *) var)-> fun(); are valid, but not good practice. You should use C++ style casting ( static_cast, dynamic_cast..) instead of c-style casting.

    ((derived2 *) var)-> fun(); is not valid, as var is not really of class derived2. It will fail if you use dynamic_cast for casting. But here it works because of object alignment in C++. In the code section, normally the derived members are laid, following the base members, and in the sequence that they are defined. So, derived1::fun and derived2::fun will be started from same offset in this case, and hence calling it works. although the object after casting to derived2* is invalid, it works since fun does not access any member of the class. But this behavior is unpredictable, and must not rely on this or use this kind of code.