Inheritance and Implicit Type Casting

Posted by Josué Molina on Stack Overflow See other posts from Stack Overflow or by Josué Molina
Published on 2012-12-01T10:27:24Z Indexed on 2012/12/01 11:04 UTC
Read the original article Hit count: 188

Filed under:

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?

© Stack Overflow or respective owner

Related posts about c++