Why do we need virtual functions in C++?

前端 未结 26 3129
北恋
北恋 2020-11-21 05:50

I\'m learning C++ and I\'m just getting into virtual functions.

From what I\'ve read (in the book and online), virtual functions are functions in the base class that

26条回答
  •  礼貌的吻别
    2020-11-21 06:05

    The bottom line is that virtual functions make life easier. Let's use some of M Perry's ideas and describe what would happen if we didn't have virtual functions and instead only could use member-function pointers. We have, in the normal estimation without virtual functions:

     class base {
     public:
     void helloWorld() { std::cout << "Hello World!"; }
      };
    
     class derived: public base {
     public:
     void helloWorld() { std::cout << "Greetings World!"; }
     };
    
     int main () {
          base hwOne;
          derived hwTwo = new derived();
          base->helloWorld(); //prints "Hello World!"
          derived->helloWorld(); //prints "Hello World!"
    

    Ok, so that is what we know. Now let's try to do it with member-function pointers:

     #include 
     using namespace std;
    
     class base {
     public:
     void helloWorld() { std::cout << "Hello World!"; }
     };
    
     class derived : public base {
     public:
     void displayHWDerived(void(derived::*hwbase)()) { (this->*hwbase)(); }
     void(derived::*hwBase)();
     void helloWorld() { std::cout << "Greetings World!"; }
     };
    
     int main()
     {
     base* b = new base(); //Create base object
     b->helloWorld(); // Hello World!
     void(derived::*hwBase)() = &derived::helloWorld; //create derived member 
     function pointer to base function
     derived* d = new derived(); //Create derived object. 
     d->displayHWDerived(hwBase); //Greetings World!
    
     char ch;
     cin >> ch;
     }
    

    While we can do some things with member-function pointers, they aren't as flexible as virtual functions. It is tricky to use a member-function pointer in a class; the member-function pointer almost, at least in my practice, always must be called in the main function or from within a member function as in the above example.

    On the other hand, virtual functions, while they might have some function-pointer overhead, do simplify things dramatically.

    EDIT: There is another method which is similar by eddietree: c++ virtual function vs member function pointer (performance comparison) .

提交回复
热议问题