class BaseClass1
{
public:
void function1()
{
cout << "Function1 BaseClass1" << endl;
}
};
class DerivedClass : public BaseClass1
{
public:
void function1()
{
cout << "Function1 DerivedClass" << endl;
}
};
int main()
{
DerivedClass d1;
d1.function1();
}
Does DerivedClass::function1() override BaseClass1::function1()?
Youtuber claimed that DerivedClass::function1() overrides BaseClass1::function1() and I thought that didn't sound right. I thought the code prints "Function1 DerivedClass" because the static type of d1 is DerivedClass.
My understanding is that function overriding doesn't occur unless the base class declares function1() as virtual.
My counter argument was that if overriding did occur then for this code snippet:
1 2 3
DerivedClass dc1;
BaseClass1 *bc1ptr = &dc1;
bc1ptr->function1(); // This line would print "Function1 DerivedClass", which it doesn't.
Maybe it was by luck that I produced this counter example but I don't understand why bc1ptr->function1() calls BaseClass1::function1(). Yet another example of slicing?
That is how unqualified name lookup works. The type of bc1ptr is 'pointer to BaseClass1' ; so the scope of BaseClass1 is looked up to resolve the call.