Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a 'Base Class object' call it's own virtual function? C++

I've read about virtual functions in C++ and understood how they provide the programmer with access to the member function of derived class using a pointer of base class. (aka Polymorphism).

The questions that have been bothering me are:

  1. Why declare a function with a same name in the base class, if in the end it has to be declared virtual? (Note: I need answers with respect to the polymorphism aspect of virtual functions)
  2. In the code below, if 'virtual display()' is called with a base class pointer (Line 22), it shows an error. Why are virtual functions in C++ so rigid w.r.t. not getting called by base class pointers?

.

#include <iostream>
using namespace std;

class B
{
    public:
       void virtual display()
         { cout<<"Inside base class.\n"; }

};

class D : public B
{
    public:
       void display()
         { cout<<"Inside derived class.\n"; }
};

int main()
{
    B *b;
    D d;

//Line-22    b->display();  Why can't 'b' call it's own display()?

    b = &d; 
    b->display();

    system("pause");
    return 0;
}

Output:

Inside derived class.

like image 576
vanguard69 Avatar asked Nov 01 '22 17:11

vanguard69


1 Answers

b is a pointer not an object. Initially it didn't point to anything (so indirecting through it is an error); after b = &d, it points to a D object, so using it to call a virtual function will call D's override.

The virtual dispatch mechanism is defined so that the function is chosen based on the type of the actual object that the pointer points to, not the declared type of the pointer. So if it pointed to a B object then it would call B::display; here, it points to a D object, so it calls D::display.

Why declare a function with a same name in the base class, if in the end it has to be declared virtual?

It needs to be declared in the base class so that, when using a pointer to the base class, the compiler knows that it exists. Whether calling the function through the pointer will call the base-class version, or a version overridden by a derived class, depends on the type of the object.

In the code below, if virtual display() is called with a base class pointer (Line 22), it shows an error.

That's because it doesn't point to anything, so using it is an error. If it were to point to a B object, then it would call the function declared in B.

B b_obj;
b = &b_obj;
b->display();   // "Inside base class"

Why are virtual functions in C++ so rigid w.r.t. not getting called by base class pointers?

They're not; that's the usual way of calling them. But the pointer must point to a valid object for virtual dispatch to work.

like image 135
Mike Seymour Avatar answered Nov 15 '22 04:11

Mike Seymour