Question

I was wondering if this (above title) is exactly possible when it comes to inheriting from an interface within C++.

class Animal
{
   public:
      virtual void Eat(Animal& a) = 0; //Function that attempts to eat an animal.
}

class Dog : Animal
{
   public:
       void Eat(Animal& a);
}

void Dog::Eat(Animal& a)
{
    Dog d = (Dog) a;
    // Do something.
}

int main()
{
   Dog dog1 = Dog();
   Dog dog2 = Dog();

   dog1.Eat(dog2);
   return;
}

So basically, I know that the animal that my dog is going to be eating is only other dogs (in all cases ever, not just in this specific example). However, I am inheriting from a purely virtual class Animal which requires me to define the function with the Animal parameter.

I know that having a parameter as Animal causes the function Dog::Eat to think that the parameter is an Animal and not a Dog. However, considering that the data for the object to be represented as a Dog is still there I am pretty sure that there is a way to establish (cast, etc) the Animal as a Dog, I just don't know how and I am not quite sure how to search.

So I am wondering how I would do this. I am pretty sure that you can use a dynamic cast or a reinterpret cast, but I am under the impression that you typically want to minimize the use of these casts if you can. I am pretty new to Object Oriented within C++ since I used to mainly use only C.

Was it helpful?

Solution

You can indeed cast it (assuming you intended Dog to be derived publicly from Animal); but you would have to cast a reference or pointer. Your cast to a value would try to create a new Dog from the Animal that was passed in; and there is no suitable conversion for that.

// safest, if you can't guarantee the type
Dog & d = dynamic_cast<Dog&>(a);  // throws if wrong type
Dog * d = dynamic_cast<Dog*>(&a); // gives null if wrong type

// fastest, if you can guarantee the type
Dog & d = static_cast<Dog&>(a);   // goes horribly wrong if wrong type

Don't use reinterpret_cast; that allows all sorts of crazy conversions, so it's easy to do something wrong. Don't use the C-style cast (Dog&)a either - that allows even more conversions than reinterpret_cast, and has a syntax that's subtle and difficult to search for.

In general, you shouldn't need a cast at all - try to design the base class so that it exposes everything you want to do with it, with no need to know the actual object type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top