Can I call a base class's virtual function if I'm overriding it?
Say I have classes 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 1:
The C++ syntax is like this:
class Bar : public Foo {
// ...
void printStuff() {
Foo::printStuff(); // calls base class' function
}
};
Solution 2:
Yes,
class Bar : public Foo
{
...
void printStuff()
{
Foo::printStuff();
}
};
It is the same as super
in Java, except it allows calling implementations from different bases when you have multiple inheritance.
class Foo {
public:
virtual void foo() {
...
}
};
class Baz {
public:
virtual void foo() {
...
}
};
class Bar : public Foo, public Baz {
public:
virtual void foo() {
// Choose one, or even call both if you need to.
Foo::foo();
Baz::foo();
}
};
Solution 3:
Sometimes you need to call the base class' implementation, when you aren't in the derived function...It still works:
struct Base
{
virtual int Foo()
{
return -1;
}
};
struct Derived : public Base
{
virtual int Foo()
{
return -2;
}
};
int main(int argc, char* argv[])
{
Base *x = new Derived;
ASSERT(-2 == x->Foo());
//syntax is trippy but it works
ASSERT(-1 == x->Base::Foo());
return 0;
}