J
johnbrown105
Hello All,
I did try searching the archives, but the topics seemed to be mostly
about base
and derived classes.
I have reached Chapter 8 in Bruce Eckel's "Thinking in C++ 2nd Edition
Vol. 1".
Question 28 says:
"Create a class called bird that can fly( ) and a class rock that
can't. Create
a rock object, take its address, and assign that to a void*. Now take
the void*,
assign it to a bird* (you'll have to use a cast), and call fly( )
through that
pointer. Is it clear why C's permission to openly assign via a void*
(without a cast) is a "hole" in the language, which couldn't be
propagated
into C++?"
I came up with:
#include <iostream>
using namespace std;
class Bird{
public:
void fly(){ cout << "Flying..." << endl; }
};
class Rock{
double d;
};
int main()
{
Rock r;
void *v = &r;
Bird *pb = reinterpret_cast<Bird*>(v);
pb->fly();
return 0;
}
This compiled and linked without warnings, as I expected. I understand
why
you should not be allowed to convert a Rock to a Bird (unless you
really, really
want to very badly).
What I did *not* expect was that it would run, but it did. Why don't
I get
a run-time error when I call fly() in my Rock masquerading as a Bird?
I tried it with gcc 3.4.2 (MingW Windows port) and 4.1.1
(http://oss.netfarm.it/mplayer-win32.php) and it worked in both cases.
I am on Windows XP SP2.
I did try searching the archives, but the topics seemed to be mostly
about base
and derived classes.
I have reached Chapter 8 in Bruce Eckel's "Thinking in C++ 2nd Edition
Vol. 1".
Question 28 says:
"Create a class called bird that can fly( ) and a class rock that
can't. Create
a rock object, take its address, and assign that to a void*. Now take
the void*,
assign it to a bird* (you'll have to use a cast), and call fly( )
through that
pointer. Is it clear why C's permission to openly assign via a void*
(without a cast) is a "hole" in the language, which couldn't be
propagated
into C++?"
I came up with:
#include <iostream>
using namespace std;
class Bird{
public:
void fly(){ cout << "Flying..." << endl; }
};
class Rock{
double d;
};
int main()
{
Rock r;
void *v = &r;
Bird *pb = reinterpret_cast<Bird*>(v);
pb->fly();
return 0;
}
This compiled and linked without warnings, as I expected. I understand
why
you should not be allowed to convert a Rock to a Bird (unless you
really, really
want to very badly).
What I did *not* expect was that it would run, but it did. Why don't
I get
a run-time error when I call fly() in my Rock masquerading as a Bird?
I tried it with gcc 3.4.2 (MingW Windows port) and 4.1.1
(http://oss.netfarm.it/mplayer-win32.php) and it worked in both cases.
I am on Windows XP SP2.