T
trying_to_learn
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)
{rock rockObj;
void * voidptr=&rockObj;
bird* birdptr=(bird*)voidptr;
//!bird* birdptr=voidptr;//illegal
birdptr->fly();
}
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)
{rock rockObj;
void * voidptr=&rockObj;
bird* birdptr=(bird*)voidptr;
//!bird* birdptr=voidptr;//illegal
birdptr->fly();
}