Re: Is it legal code?
"Gerhard Fiedler" <gelists@gmail.com> wrote in message
news:47hao38wygfk$.dlg@gelists.gmail.com...
Paul wrote:
What is undefined about the normal function I posted ref:
void ordinaryfunction(p_obj){
overwrite(p_obj); /*overwrite the object p_obj points to*/
ordinaryfunction();
}
In an earlier incarnation of this you specifically used assembly to
overwrite p_obj in overwrite(). This is of course undefined behavior.
If you want to get anywhere with this argument, you'd have to start
using standard-conformant, compilable C++. The above is neither.
How exactly will you "overwrite" the class instance at p_obj?
Try to come up with a standard C++ example that involves a class and a
function operating on an instance of that class. I'm pretty sure that it
is possible to re-write that example using a member function. And vice
versa.
I used an example which made a new object in the same memory location,
with a theoretical asm routine. The reason I did it this way was to
emphasise the fact that the 'this' pointer was not even being
adjusted.[Note: Because I had the feleling someone would try to be
unreasonable and expect my code to comply with standards whereas the
other argument didn't comply, so I did it a way that my code *did
comply* anyway.. End note]
As long as we're talking about C++, we should stick to the C++ standard
-- or else what language are you /really/ talking about?
Are you saying its illegal to overwrite an object? Please make your point
clear.
It's not; we have assignment operators for that. It is you who is trying
to make a point that it's not possible to overwrite a class instance.
Before straying too far form the original subject please note that if
my ordinary function is valid C++ code ...
But so far it isn't. You have to do more work on this.
I think this proves the same point using standard C++ code:
#include <iostream>
class Animal{public:
virtual void eat(){std::cout<< "Animal Eating"<< std::endl;}
virtual int getID()=0;
static int count;
};
class Dog: public Animal{
public:
void eat(){std::cout<< "Dog Eating"<< std::endl;}
int getID(){return 1;}
};
class Cat: public Animal{
public:
void eat(){std::cout<< "Cat Eating"<< std::endl;}
int getID(){return 0;}
};
int Animal::count =10;
Dog* overwriteCat(Animal* ptr){
delete ptr;
Dog* p = reinterpret_cast<Dog*>(ptr);
p = new Dog;
return p;
}
Cat* overwriteDog(Animal* ptr){
delete ptr;
Cat* p = reinterpret_cast<Cat*>(ptr);
p = new Cat;
return p;
}
void ordinary_function(Animal* obj){
Animal::count--;
std::cout<<"Address of obj: " <<obj << " ";
obj->eat();
if(obj->getID()){overwriteDog(obj);}
else {overwriteCat(obj);}
if(Animal::count){
ordinary_function(obj);
}
}
int main()
{
Cat* p_cat = new Cat;
Animal* p_anim = p_cat;
ordinary_function(p_cat);
}