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++?
Because virtual functions are called only for objects of class types, you cannot declare global or static functions as virtual . The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual.
To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.
Yes, you need to use the override keyword, otherwise the method will be hidden by the definition in the derived class.
When you want to call a specific base class's version of a virtual function, just qualify it with the name of the class you are after, as I did in Example 8-16: p->Base::foo(); This will call the version of foo defined for Base , and not the one defined for whatever subclass of Base p points to.
The C++ syntax is like this:
class Bar : public Foo { // ... void printStuff() { Foo::printStuff(); // calls base class' function } };
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(); } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With