"Subhransu Sahoo" <sy******@gmail.comwrote in message
news:11**********************@m73g2000cwd.googlegr oups.com...
: Hi All,
:
: Can anyone tell me why the output of the following program is fx1 fx2
?
The program is triggering undefined behavior
(when using the result of reinterpret_cast).
The outcome you are observing is the accidental result of
one implementation approach for virual functions that your
compiler is using, and goes beyond the scope of this newsgroup.
: #include <iostream>
: using namespace std;
:
: class IX
: {
: public:
: virtual void fx1() {cout<<"fx1"<<endl;}
: virtual void fx2() {cout<<"fx2"<<endl;}
: };
:
: class IY
: {
: public:
: virtual void fy1() {cout<<"fy1"<<endl;}
: virtual void fy2() {cout<<"fy2"<<endl;}
: };
:
: class CA :public IX, public IY {};
:
: void main()
NB: return type of main() shall be int in standard C++.
: {
: IY *yobj = reinterpret_cast<IY*>(static_cast<IX*>(new CA));
: yobj->fy1();
: yobj->fy2();
: }
To get the behavior you (probably) expect, use dynamic_cast:
IY *yobj = dynamic_cast<IY*>(static_cast<IX*>(new CA));
Only use reinterpret_cast when you really know what you are doing...
hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <
http://www.brainbench.com