-5

Here in the code i am able to successfully point a derived class pointer to a base class object and I m also able to set and get value of the base class private member. If this is not giving any issues then what is the need of virtual functions and the whole confusion around run time polymorphism/late binding/vtable bla bla bal!!!

#include <iostream>
using namespace std;

class Base
{
    int a;
public:
    Base(int x=0):a(x){}
    void setValueForMember(int p)
    {
        a=p;
    }
    void showValueOfMember(){cout<<endl<<a<<endl;}
};

class Derived:public Base
{
    int b;
public:
    Derived(){}
    Derived(int y):b(y){}
    void setValueForMember(int q)
    {
        b=q;
    }
    void showValueOfMember(){cout<<endl<<b<<endl;}
};

int main()
{
    Derived D;
    D.setValueForMember(10);
    Derived *Dptr = new Derived();
    Dptr = &D;
    Dptr->showValueOfMember();
    Base B;
    Dptr = (Derived*)&B;
    Dptr->setValueForMember(20);
    Dptr->showValueOfMember();
    return 0;
}
Kijewski
  • 25,517
  • 12
  • 101
  • 143

1 Answers1

0

Virtual function is used in the case when , we want to access the members of the derived class using the pointer of type, base class.

  • when you will use

Bptr=&D;

you won't be able to access the members of Derived class , except the members inherited from the Base class. If you want to access the members of the Derived class using the same pointer that is Bptr, you must have to use virtual function,

  • and at the time of compilation it is decided that which function is going to be executed, that's why it is known as

Run-Time polymorphism or Dynamic Binding

.

tilak
  • 137
  • 2
  • 9