Suppose I have the following three classes:
class Animal {};
class Human : public Animal {};
class Dog : public Animal
{
public:
void setOwner(Animal* owner) { this->owner = owner; }
private:
Animal* owner;
};
Why is the following allowed, and what exactly is happening?
Dog d;
Human h;
d.setOwner(&h); // ?
At first, I tried to cast it like this d.setOwner(&(Animal)h), but the compiler gave me a warning, and I hit a run-time error.
Edit: the warning the compiler gave me was “taking address of temporary”. Why is this so?
Here
d.setOwner((Animal)&h)
you try to case pointer type to object type. You cannnot do this.
Correct way of casting to Animal class is
But you
This
works because pointers in C++ are automatically cast to a base class if needed. Explicit conversion to Animal* is not needed.