overload resolution clarification

S

sri

class Base
{
public:
virtual void f(int) { std::cout<<"base.f(int)\n";};
virtual void f(std::complex<double>) { std::cout<<"derived.f
\n"; };
};

class Derived : public Base
{
public :
virtual void f(double) {std::cout<<"base.f(double)\n";};
};

int main()
{

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

the above program is calling f(int) version, why the overloading
resolution is calling f(int) version in Base class?

with Regards,
Sri
 
V

Victor Bazarov

sri said:
class Base
{
public:
virtual void f(int) { std::cout<<"base.f(int)\n";};
virtual void f(std::complex<double>) { std::cout<<"derived.f
\n"; };
};

class Derived : public Base
{
public :
virtual void f(double) {std::cout<<"base.f(double)\n";};
};

int main()
{

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

the above program is calling f(int) version, why the overloading
resolution is calling f(int) version in Base class?

Instead of which one, the 'complex'? User-defined conversion sequence
(float to std::complex<double>) has lower rank than standard (floating-
integral) conversion, according to 13.3.3.2/2.

V
 
J

James Kanze

class Base
{
public:
virtual void f(int) { std::cout<<"base.f(int)\n";};
virtual void f(std::complex<double>) { std::cout<<"derived.f
\n"; };
};
class Derived : public Base
{
public :
virtual void f(double) {std::cout<<"base.f(double)\n";};
};
int main()
{
Base b; //Line 1
Derived d; //Line 2
Base* pb = new Derived; //Line 3
pb->f(1.0f); //Line 4
return 0;
}
the above program is calling f(int) version, why the overloading
resolution is calling f(int) version in Base class?

And what should it call? Overload resolution is done by the
compiler, at compile time, and so can only consider the static
type of the epxression. In this case, Base. There are two f in
Base, f(int) and f(complex<double>). The conversion double to
complex<double> formally involves a user defined conversion;
according to the rules, the compiler chooses a built-in
conversion over a user defined conversion, even if the built-in
conversion is lossy, as it is here.

And of course, since the static type is Base, the compiler
doesn't see the f(double) in derived at all.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top