Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ is there a way to give error if a function that takes a class type is passed a derived type instead?

Tags:

c++

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;
}
like image 295
SolarisPol Avatar asked Dec 15 '25 04:12

SolarisPol


2 Answers

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`.");
    }
    // ...
}
like image 105
NicholasM Avatar answered Dec 16 '25 19:12

NicholasM


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.

like image 30
eerorika Avatar answered Dec 16 '25 19:12

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!