Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++?

like image 338
Alex Avatar asked Mar 23 '09 06:03

Alex


People also ask

Can you override a virtual function?

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.

How do you call a base class function in a function overriding?

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.

Is it mandatory to override virtual methods of base class?

Yes, you need to use the override keyword, otherwise the method will be hidden by the definition in the derived class.

How do you call a virtual function in base 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.


2 Answers

The C++ syntax is like this:

class Bar : public Foo {   // ...    void printStuff() {     Foo::printStuff(); // calls base class' function   } }; 
like image 76
sth Avatar answered Oct 14 '22 03:10

sth


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();     } }; 
like image 41
Alex B Avatar answered Oct 14 '22 01:10

Alex B