Reputation: 103
Is there a way to give an error if a function that takes a class type is passed a derived type instead? Couldn't find a duplicate of this, perhaps because polymorphism is at the heart of C++. Example:
class Base
{
int a;
};
class Derived : public Base
{
};
int MySpecialFunc(Base &_a) // I want an error/not compile if 'Derived' is passed instead of 'Base'
{
return 1;
}
Upvotes: 2
Views: 103
Reputation: 4673
You could do an exact type check at runtime with typeid
.
However, I would seriously question the underlying motivation for this kind of check. People often recommend that inheritance be consistent with the Liskov substitution principle.
What you're proposing is that even when a derived class is perfectly Liskov-substitutable for the base class, this function is going to second-guess that substitutability. It will almost certainly limit extensibility of the base class.
int MySpecialFunc(Base& a)
{
if (typeid(a) != typeid(Base))
{
throw std::runtime_error("Type is not exactly `Base`.");
}
// ...
}
Upvotes: 7
Reputation: 238311
As long as you need to limit only a finite set of types, and you only need to prevent passing directly, then overloading would work:
int MySpecialFunc(Derived &) = delete;
It is possible to get around the restriction with a static cast of the reference though.
Upvotes: 4