Re: Question about inheritance in c++
Dotanitis@gmail.com wrote:
On Mar 11, 8:35 am, John Harrison <john_androni...@hotmail.com> wrote:
Dotani...@gmail.com wrote:
Hello everyone,
I wrote:
class CA{
public:
CA() {number = 1;}
~CA() {}
int number;
};
class CB : public CA
{
public:
CB(){number = 2;}
~CB()
void foo(){
uid++;
cout<<"uid:"<<uid<<endl;}
};
void main()
{
CA* a1 = new CA();
((CB*) a1)->foo();
}
OK, i pass compilation phase & runtime phase the output was
"uid:-23847298":
questions:
1. why i pass the runtime phase? CA class have no "uid" member.
It doesn't but you used a cast to fool the compiler.
2. how can i protect this code and make this program fail in the
compilation phase?
C++ isn't that sort of language, you don't get the protection you do in
some languages. The simple advice is don't use casts, or when you must
use them, use C++ casts instead of C casts, they're a little bit safer.
john
Thanks,
1. why it does'nt crush on the runtime phase?
When you break the rules of C++ usually what you get is 'undefined
behaviour'. Undefined behaviour means anything could happen with your
program. It could run, it could crash, it could run but print out
garbage, anything can happen. If you do this kind of thing too often I
promise you that your programs will crash, but they are not *required*
to crash.
2. can you show me the differ from c casting style & c++?
C++ has four new styles of cast.
static_cast<CB*>(a1)->foo();
reinterpret_cast<CB*>(a1)->foo();
const_cast<CB*>(a1)->foo();
dynamic_cast<CB*>(a1)->foo();
They are all designed to do one kind of casting, and if you use them to
do a different kind of casting you will get a compile error.
static_cast is for related types (it would work in your example because
CB inherits from CA but it wouldn't work if CB and CA were unrelated)
reinterpret_cast is for unrelated types, it works pretty much anytime
and is closest to the C style cast.
But even reinterpret_cast cannot remove const, const_cast is for that.
Finally dynamic_cast is something new. It is for polymorphic types (i.e.
classes with virtual functions) and determines at runtime whether a cast
can be made.
john
dotan