A little help with inheritance and a virtual functions

Hi guys, if you derive from a class, how do you ensure that when you override a virtual method for that class; the base class (default) method also gets executed?
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
#include <iostream>

class base {
public:
    virtual void sayName() {
        std::cout << "Base";
    }
    
    virtual ~base() {}
};

class derived : public base {
    void sayName() {
        std::cout << "Derived" << std::endl;
        base::sayName();
    }
};

int main() {
    base *b = new derived();
    b->sayName();
    
    delete b;
    b = new base();
    std::cout << std::endl << std::endl;
    b->sayName();
    
    delete b;
    
    return 0;
}
As @Smac89 demonstrates, you call the function itself but you prefix the name with the name of the base class and the scope resolution operator ::
1
2
3
4
5
6
virtual void myfunc() override
{
    //...
    BaseClass::myfunc();
    //...
}
You can call any functions up the inheritance chain this way, even in outside code.
Last edited on
Topic archived. No new replies allowed.