简体   繁体   中英

Strange behavior of pure virtual function

#include <iostream>
using namespace std;

class B
{
    B();

public:
    virtual void print()=0;
};

void B::print()
{
    cout << "B::print"; 
}

int main()
{ 
   B *bp;
   bp->B::print();  /* Type-A   works fine */
   bp->print();     /* Type-B   segmentation fault */

   return 0;
}

In the above code I am trying to invoke pure virtual function via 'bp'. Now in main function there are two types of call (Type-A, Type-B). My question is why A works but B doesn't. Moreover why compiler allows to invoke a non-static function without creating an object.

bp doesn't point to a valid object so you're experiencing undefined behavior. In this case, A works but B doesn't is a perfectly valid undefined behavior. Note that you couldn't make bp point to an object of type B because it's an abstract type. If you derived another class and implemented print then you could point bp at that child object.

Both are undefined behavior, and anything can happen. bp is not initialized, so calling methods on it or dereferencing it is illegal.

The point:

  1. bp->B::print() might work because: B::print() is explictly given and has a valid pointer, and the function itself does not involve with *this pointer. It will be translated to B::print(bp) and bp is neglected.

  2. bp->print() might not work because the code will look for vptr of the object bp points to, which does not exist. The vptr gives a wrong position to vtable and the function call will fail. It is translated into sth. like : bp->vptr->vtable['print'](bp)' and you can see both vptr and vtable` not defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM