Can a base class function be overriden if it isn't declared virtual?

I wanted to verify something that was said in a youtube video. Code below is what was presented.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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?
Last edited on
> Does DerivedClass::function1() override BaseClass1::function1()?

No.


> I thought the code prints "Function1 DerivedClass" because the static type of d1 is DerivedClass.

Yes.


> why bc1ptr->function1() calls BaseClass1::function1()?

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.
Last edited on
Thanks JLBorges. That's new to me.
Topic archived. No new replies allowed.