A
Alex Vinokur
Here is some program in which static_cast is (wrongly) used instead of dynamic_cast.
Is output of the program undefined or predicted?
=========== C++ code : foo.cpp : BEGIN ===========
#include <iostream>
using namespace std;
struct B
{
virtual void foo1 () { cout << "B::foo1" << endl; }
virtual void foo2 () { cout << "B::foo2" << endl; }
};
struct D1 : public B
{
void foo1 () { cout << "D1::foo1" << endl; }
};
struct D2 : public B
{
void foo2 () { cout << "D2::foo2" << endl; }
};
int main ()
{
B* pB = new D1;
// --------------------------
// Of course, here we should use dynamic_cast
D2* pD2 = static_cast<D2*> (pB);
// --------------------------
pD2->foo1();
pD2->foo2();
return 0;
}
=========== C++ code : foo.cpp : END =============
=========== Compilation & Run : BEGIN =============
$ g++ --version
g++ (GCC) 3.3.3 (cygwin special)
[---omitted---]
$ g++ -W -Wall foo.cpp
// No errors, no warnings
$ a
D1::foo1
B::foo2
=========== Compilation & Run : END ===============
Is output of the program undefined or predicted?
=========== C++ code : foo.cpp : BEGIN ===========
#include <iostream>
using namespace std;
struct B
{
virtual void foo1 () { cout << "B::foo1" << endl; }
virtual void foo2 () { cout << "B::foo2" << endl; }
};
struct D1 : public B
{
void foo1 () { cout << "D1::foo1" << endl; }
};
struct D2 : public B
{
void foo2 () { cout << "D2::foo2" << endl; }
};
int main ()
{
B* pB = new D1;
// --------------------------
// Of course, here we should use dynamic_cast
D2* pD2 = static_cast<D2*> (pB);
// --------------------------
pD2->foo1();
pD2->foo2();
return 0;
}
=========== C++ code : foo.cpp : END =============
=========== Compilation & Run : BEGIN =============
$ g++ --version
g++ (GCC) 3.3.3 (cygwin special)
[---omitted---]
$ g++ -W -Wall foo.cpp
// No errors, no warnings
$ a
D1::foo1
B::foo2
=========== Compilation & Run : END ===============