inheritance function override question

I am trying to use polymorphism to override a function.
In the following example, I want Der::print() to override Base::print().
I expect der.func() to print "Class Der", but it prints "Class Base".
What am I missing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

class Base
{
public:
    void func()
    {
	    print();
    }

    void print()
    {
	    std::cout << "Class Base" << std::endl;
    }
};

class Der : public Base
{
public:
    void print()
    {
	    std::cout << "Class Der" << std::endl;
    }
};

int main()
{
    Base base;
    Der der;

    base.func();
    der.func();

    return 0;
}

output:
Class Base
Class Base

Thank you in advance.
In the base class, make it virtual void print() instead of just void print().

You can do the same in the derived class as well if you want, but it's not strictly necessary.
Thanks long double main, that worked!
Topic archived. No new replies allowed.