A little help with inheritance and a virtual functions
Apr 15, 2015 at 5:32pm UTC
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?
Apr 15, 2015 at 5:48pm UTC
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;
}
Apr 15, 2015 at 6:15pm UTC
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 Apr 15, 2015 at 6:16pm UTC
Topic archived. No new replies allowed.