0
votes

Suppose that I have a base class pointer, with base class having virtual functions. And if I am pointing a derived class object using base class pointer then how compiler knows that it is derived version of that virtual function to be called since at the time of assignment the derived class address would have been converted into base class type, why doesn't compiler generate an error since memory layout of both may be different.

And also if I have declared base class destructor virtual and deleting the base pointer having address of derived class then how does compiler know that I am actually deleting the derived object.

class a{
public:
virtual ~a(){}
virtual void f(){}
};
class b:public a
{
  public:
  ~b(){}
  void f(){ cout<<"hi";}
};
main()
{
  a *aptr;
  aptr=new b;   //here aptr has the address of b;
  delete aptr;  //since pointer type is base class so how will compiler know that
                //it has to call derived's destructor,also their names are different
                //as one is a and another is b. 
} 
2
The short answer is that it's not your concern how it works (especially while you still think that main() without return type is acceptable C++); all that matters is that the standard says that it will work.Kerrek SB
You forgot main's return type there, Skippy.Lightness Races in Orbit
Actually, this shouldn't work, because the base has no virtual destructor.Björn Pollex
@KerrekSB it will not work.Luchian Grigore
Yeah I forgot, now changedAzazle

2 Answers

1
votes

To actually delete a derived class through a base pointer you need to declare the destructor virtual. Otherwise havoc will ensue (actually undefined behavior, which is about the same).

As for how virtual functions are implemented: it is up to the implementation. Without asking about a specific implementation a real answer is not possible. The most likely implementation are vtables.

1
votes

It won't (or it will). It's undefined behavior deleting an object of derived type through a pointer to a base type without a virtual destructor.