The following C++ code demonstrates what I mean in more detail.
#include <iostream>
using namespace std;
class Animal
{
public:
int animal_property = 20;
};
class Cat: public Animal
{
public:
int cat_property = 10;
};
void test(Cat c)
{
cout << "Inside test" << endl;
}
int main()
{
Animal hybrid = Cat();
// cout << hybrid.cat_property << endl; -- Breaks
// cout << test(hybrid) << endl; -- Breaks
return 0;
}
In this example I have created a Cat()
object, but limited its type visibility to Animal
. This means I can no longer access any properties or functions on the Cat
class, despite originally defining it as Cat()
. I cannot also pass the object to a function which requires a Cat
.
What are the benefits of doing this and how does it differ to simply comparing it to Animal animal = Animal()
, are their any design patterns where this is useful?