You are here:

C++/Virtual Function

Advertisement


Question
#include <iostream>
#include <complex>

using namespace std;

class Base
{
  public:
  virtual void f(int x)
  {
     cout<<"in int"<<endl;
  }

  void f(std::complex<double> x)
  {
     cout<<"in complex"<<endl;
  }

};

class Derived : public Base
{
  public :
   void f(double x)
  {
     cout<<"in double"<<endl;
  }
};

void main()
{
  Base b;         //Line 1
  Derived d;         //Line 2
  Base*  pb = new Derived;   //Line 3
  pb->f(1.0f);         //Line 4
}

The output is "in int" I am unable to understand why I am getting that output.
I was expecting to print "in float"
Can you please explain ...?

Answer
In the code you showed in your question no member function produces output "in float" so it is not surprising that this is not output.

I suspect however that you were expecting "in double" and "in float" was a typo or that the code either that you were using or you posted was not in sync with the text of the question. I shall proceed assuming you were expecting "in double".

The reason is that you are confusing function overloading with virtual (member) function overriding. When you override a virtual function the signature of the overriding function _must_ _match_ that of the base class virtual member function it is overriding. This is not the case here:

   class Base
   {
   public:
       virtual void f(int x)
       {
         cout<<"in int"<<endl;
       }

       void f(std::complex<double> x)
       {
         cout<<"in complex"<<endl;
       }
   };

   class Derived : public Base
   {
   public:
       void f(double x)
       {
         cout<<"in double"<<endl;
       }
   };

Here the base class virtual function f has the signature:

   void f(int)

Whereas the derived class member function f has the signature:

   void f(double)

The two do not match so the void Derived::f(double) function does _not_ override the void Base::f(int) function. Instead the void Derived::f(double) function is an ordinary member function, and provides a further overload of the function name f for objects of type Derived _only_ - objects of type Base do _not_ have this overload.

To override void Base::f(int) Derived would need a function such as:

   class Derived : public Base
   {
   public:
       void f(int x)
       {
         cout<<"in Derived int"<<endl;
       }
   };

Thus when calling f on a Derived instance through a pointer to Base only those member functions that are part of the Base class are considered. Two candidates are found:

   void f(int)
   void f(std::complex<double>)

First note that both functions have one parameter so both match the function call on this point.

Second, as neither of these is an exact match for the type of the passed argument value the rules for overload resolution come into play. This is a fairly complex topic when looked at in detail, but in short:

Two conversions will be required to convert the float argument value to a std::complex<double>: promote float to double, convert double to std::complex<double>. This requires a user defined conversion - the conversion of double to the std::complex<double> class by calling the relevant constructor and creating a temporary instance of std::complex<double>.

The conversion of float to int requires only a single standard conversion - a floating integral conversion of float to int.

In the rules for overload resolution laid down in the C++ standard a standard conversion beats a conversion that requires a user defined conversion, so the conversion to int case wins and the

   void f(int)

function is selected as the target of the call in the line:

   pb->f(1.0f);         //Line 4

Thus when run the above line resolves to a call to void Base::f(int) with 1.0f converted to 1, and "in int" is output.

Hope this helps.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.