-3

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?
}
quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107

2 Answers2

1

((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.

Rakib
  • 7,435
  • 7
  • 29
  • 45
0

First of all, here base * var = new derived1; you are up-casting.

Second, It's safer to use dynamic_cast for the down-castings.

derived1 *d1 = dynamic_cast<derived1*>(var);
if(d1) d1->fun();
derived2 *d2 = dynamic_cast<derived2*>(var); // will return NULL
if(d2) d2->fun();
101010
  • 41,839
  • 11
  • 94
  • 168
  • 1
    You know there is a big problem in a piece of code when your answer to a question about it is "I recommend to use dynamic_cast"... – Griwes May 20 '14 at 09:02
  • @Griwes I'm not a native speaker, you think that "recommend" should be removed? – 101010 May 20 '14 at 09:04
  • @40two I get it, I am just wondering if my way of downcasting is acceptable or not, thought it is working but is that acceptable? – user3655742 May 20 '14 at 09:04
  • I think that the answer here is to tell OP how he should write his code in the first place, not letting him believe that what he does makes any kind of sense. – Griwes May 20 '14 at 09:05