Topic: Should this be allowed???
Author: raveendran.v@ap.sony.com ("Raveendran")
Date: Tue, 3 Dec 2002 14:21:41 +0000 (UTC) Raw View
Hi,
Please look at the code below,
#include <iostream.h>
class A {
public:
A() { cout << "In A CTOR"<< endl;}
~A() { cout << "In A DTOR"<< endl;}
virtual void x() {
cout << "In A's X" << endl;
}
};
class B : public A{
public:
B() { cout << "In B CTOR"<< endl;}
~B() { cout << "In B DTOR"<< endl;}
void x() {
cout << "In B's X" << endl;
}
void y() {
cout << "IN Y" << endl;
}
};
void main() {
B* bb = (B*)new A;
bb->y();
delete bb;
/*
// The output is the same in this case as well
// B* bb = reinterpret_cast<B*>(new A);
// B* bb = static_cast<B*>(new A);
bb->y();
delete bb;
*/
}
The output generated is as follows,
In A CTOR
IN Y
In B DTOR
In A DTOR
Shouldn't at least the cast operator take care of this??????
- Thanks
- Raveendran V.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Author: ark@research.att.com (Andrew Koenig)
Date: Tue, 3 Dec 2002 16:29:13 +0000 (UTC) Raw View
> Shouldn't at least the cast operator take care of this??????
If B is derived from A, and you write
B* bb = (B*)new A;
the effect is undefined.
The result of "new A" is a pointer to an A object, not a pointer
to a B object, and casting the pointer won't change that.
--
Andrew Koenig, ark@research.att.com, http://www.research.att.com/info/ark
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]