Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of virtual function in C++

I have a question, here are two classes below:

  class Base{
      public:
          virtual void toString();       // generic implementation
  }

  class Derive : public Base{
      public:
          ( virtual ) void toString();   // specific implementation
  }

The question is:

  • If I wanna subclass of class Derive perform polymophism using a pointer of type Base, is keyword virtual in the bracket necessary?

  • If the answer is no, what's the difference between member function toString of class Derive with and without virtual?

like image 388
Summer_More_More_Tea Avatar asked Apr 19 '10 17:04

Summer_More_More_Tea


People also ask

What is the virtual function in C?

A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

What are the rules of virtual function?

Rules for Virtual FunctionsVirtual functions cannot be static. A virtual function can be a friend function of another class. Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism.

Is virtual function part of polymorphism?

A virtual function is a special type of function that, when called, resolves to the most-derived version of the function that exists between the base and derived class. This capability is known as polymorphism.

What is virtual function explain characteristics of it?

A virtual function is a member function of a class, whose functionality can be overridden in its derived classes. It is one that is declared as virtual in the base class using the virtual key word. The function body of base class can be completely replaced with a new set of implementation in the derived class.


1 Answers

C++03 §10.3/2:

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

like image 126
Potatoswatter Avatar answered Oct 18 '22 15:10

Potatoswatter