"trying_to_learn" <> wrote in message
news:cmmpp5$6o1$...
> Hello All
> Have another qn from the practice exercises. I ve done the exercise and
> the birds fly member fn was called successfully. But i still cant answer
> the authors qn. why this ability to assign void * has had to be avoided in
> C++. I didnt even instantiate bird obj then how was i able to call a bird
> member fn. Im confused.
>
> Quote: "Qn)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++?" End Quote.
>
> class bird
> {
> public:
> void fly(void);
> };
> void bird::fly(void) {cout<<"Birds Fly"<<endl;}
> class rock{};
>
> //!!!!!!!!!!MAIN!!!!!!!!
> void main(void)
// should be int main()
> {rock rockObj;
> void * voidptr=&rockObj;
> bird* birdptr=(bird*)voidptr;
> //!bird* birdptr=voidptr;//illegal
> birdptr->fly();
> }
You just made a rock fly. Congratulations!
This worked because class bird doesn't have any associated data used in
bird::fly(). What this points out is that methods of C++ functions aren't
really "in the object". There is only one method which serves all objects of
that type. In other words, in C it is like this:
struct bird_data {};
void bird_fly(bird_data*) {cout<<"Birds Fly"<<endl;}
Although you don't see any argument in bird::fly, there is a hidden one
called "this" which points to the associated data. Since bird::fly doesn't
use its "this" pointer (just as bird_fly doesn't use bird_data) the function
worked. (It's still undefined behavior though, so kids, don't try this at
home.)
Your instructor is quite right to call void pointers a hole in the C++ type
system. That's what they are supposed to be, but if you use them you make
make rocks fly by accident. So don't use void pointers unless you need them
for legacy code or very low level operating system operations.
--
Cy
http://home.rochester.rr.com/cyhome/