paper.plane
paper.plane

Reputation: 1197

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.

Upvotes: 0

Views: 108

Answers (3)

xis
xis

Reputation: 24850

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 bothvptrandvtable` not defined.

Upvotes: 1

Mark B
Mark B

Reputation: 96241

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.

Upvotes: 5

Luchian Grigore
Luchian Grigore

Reputation: 258568

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

Upvotes: 4

Related Questions