Reputation: 1599
struct struct1
{};
struct struct2:public struct1
{};
class Base
{
public:
virtual void foo(struct1 *s)
{
cout<<"foo in Base"<<endl;
}
};
class Der:public Base
{
public:
virtual void foo(struct2 *s)
{
cout<<"Foo in Der"<<endl;
}
};
int main()
{
struct2 s;
Base *b = new Der();
b->foo(&s);
}
When I call the function in main It calls the member in Base."foo in Base" gets printed. It prints "foo in Der" when the Derived class function takes struct1 pointer. But Is there any way to make it take struct2 pointer and display "foo in Der"
Upvotes: 2
Views: 73
Reputation: 208456
What you are asking for, interpreting that you mean to override the behavior of Base::foo
, would be co-variant arguments to the function, and that is not possible in OO, as the derived type would be narrowing the contract of the base type, and thus it would break the Liskov Substitution Principle. You would not be able to substitute an object of type Base
with an object of type Der
, as the latter does not accept a struct1
object that is not a struct2
object.
When the derived type function has the same signature (i.e. also takes a struct1*
), then it overrides the behavior of the Base
and dynamic dispatch kicks in. But when you the signature has struct2*
it does not override but rather hides the Base
function.
Upvotes: 3