patterncppCritical
Can I call a base class's virtual function if I'm overriding it?
Viewed 0 times
functionoverridingclassvirtualbasecancall
Problem
Say I have classes
As annotated in the code, I'd like to be able to call the base class's function that I'm overriding. In Java there's the
Foo and Bar set up like this:class Foo
{
public:
int x;
virtual void printStuff()
{
std::cout << x << std::endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
// I would like to call Foo.printStuff() here...
std::cout << y << std::endl;
}
};As annotated in the code, I'd like to be able to call the base class's function that I'm overriding. In Java there's the
super.funcname() syntax. Is this possible in C++?Solution
In C++ you have to explicitly name the base class in calling the derived class method. This can be done from any method from the derived class. The override is a special case of the method of the same name. In Java there is no multi inheritance, so you can use super which will uniquely name the base class. The C++ syntax is like this:
class Bar : public Foo {
// ...
void printStuff() override { // help the compiler to check
Foo::printStuff(); // calls base class' function
}
};Code Snippets
class Bar : public Foo {
// ...
void printStuff() override { // help the compiler to check
Foo::printStuff(); // calls base class' function
}
};Context
Stack Overflow Q#672373, score: 561
Revisions (0)
No revisions yet.