Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ polymorphism, name resolution for derived class

class Base {
public:
virtual void f(float) { cout << "Base::f(float)\n"; }
};
class Derived : public Base {
public:
virtual void f(int) { cout << "Derived::f(int)\n"; }
};
int main() {
Derived *d = new Derived();
Base *b = d;
b->f(3.14F);
d->f(3.14F);
}

-C++ does not support contravaraint return type, so the f(int) does not override f(float)

-Polymorphism is supported by C++, so both d and b should point to vtable for the derived class.

-vtable for derived class is something like 0: f(float), 1: f(int) etc.

My answer for the question is Base::f(float) is called twice, but the answer is:

Base::f(float) Derived::f(int)

Why is this the case? Does accessing derived class from different pointer enforce certain rules? Far as I am aware, object slicing only occurs when using copy-ctor or copy-assignment, with pointers, they should all point to the same vtable.

like image 786
legokangpalla Avatar asked Mar 26 '26 08:03

legokangpalla


1 Answers

Methods in different classes do not overload together; defining another f() in Derived prevents the one in Base from being considered during overload resolution.

You need to explicitly bring base definitions into derived classes when you want to add new overloads without hiding the ones defined in base classes.

public:
    using Base::f;
like image 103
cdhowie Avatar answered Mar 27 '26 21:03

cdhowie



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!