In your example, some_function()
is returning an AbstractClass
by value, which means the returned object gets sliced and will always be just a AbstractClass
by itself. Polymorphism only works with pointers and references. Either way, you can use dynamic_cast
for your validation check.
For example:
AbstractClass* some_function(int argument);
...
AbstractClass *obj;
obj = some_function(1);
if (dynamic_cast<DerivedClassOne*>(obj) != NULL)
// returned the correct type...
else
// returned the wrong type...
obj = some_function(2);
if (dynamic_cast<DerivedClassTwo*>(obj) != NULL)
// returned the correct type...
else
// returned the wrong type...
Or:
AbstractClass& some_function(int argument);
...
try {
dynamic_cast<DerivedClassOne&>(some_function(1));
// returned the correct type...
}
catch (const std::bad_cast&) {
// returned the wrong type...
}
try {
dynamic_cast<DerivedClassTwo&>(some_function(2));
// returned the correct type...
}
catch (const std::bad_cast&) {
// returned the wrong type...
}