Virtual Destructors Virtual Assignment And Overriding Virtua

Virtual Destructors

You should always make your destructors virtual if you’re dealing with inheritance.

Overload vs. override vs. hide

  • To overload a function f() means to provide another function with the same name (f) in the same scope but with different parameter types. When f() is actually called, the compiler will try to pick the best match based on the actual parameters that are supplied.
  • To override a virtual function f() means to provide another function with the same name (f) and the same parameter types in a derived class.
  • To hide a function f() in an enclosing scope (base class, outer class, or namespace) means to provide another function with the same name (f) in an inner scope (derived class, nested class, or namespace), which will hide the same function name in an enclosing scope.

Example: Check the following program. What it should print and what are the problems with it?

#include <iostream> 
#include <complex>
using namespace std;
class Base
{
public:
  virtual void f( int );
  virtual void f( double );
  virtual void g( int i = 10 );
};
void Base::f( int )
{
  cout << "Base::f(int)" << endl;
}
void Base::f( double )
{
  cout << "Base::f(double)" << endl;
}
void Base::g( int i )
{
  cout << i << endl;
}
class Derived: public Base
{
public:
  void f( complex<double> );
  void g( int i = 20 );
};
void Derived::f( complex<double> )
{
  cout << "Derived::f(complex)" << endl;
}
void Derived::g( int i )
{
  cout << "Derived::g() " << i << endl;
}
void main()
{
  Base    b;
  Derived d;
  Base*   pb = new Derived;
  b.f(1.0);
  d.f(1.0);
  pb->f(1.0);
  b.g();
  d.g();
  pb->g();
  delete pb;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.