Frederigo
Frederigo

Reputation: 246

when explicit conversion is necessary and implicit will not work

When i have 2 classes with implemented conversion constructors and conversion operator is there possible situation that will require explicit conversion because implicit will not work ? (I make it example with 2 class to see if inheritance makes any difference)

Upvotes: 1

Views: 98

Answers (3)

Aditya Kashi
Aditya Kashi

Reputation: 366

As long as you have the relevant constructor

class A
{
  // ...
  A(const B& b);  // or similar
};

an implicit cast of the type

B b(...);  // B is the other class
A a = b;

or

B b(...);
A a(b);

will work.

Upvotes: 1

Sudipta Kumar Sahoo
Sudipta Kumar Sahoo

Reputation: 1147

Here is an example of inheritance where explicit type casting is mandatory:

// Base class.
class Foo
{
};

// Derived class.
class Bar : public Foo
{
public:
    void SomeMethod()
    {
        cout << "I a in Bar!" << endl;      
    }
};

// Global method; input argument is derived class pointer.
void method(Bar* obj)
{
    obj->SomeMethod();
}

// main
int main()
{
    Foo* obj1 = new Foo();

    method(obj1); // This line will error when passing the base class object
                  // error C2664: 'method' : 
                  //cannot convert parameter 1 from 'Foo *' to 'Bar *'


    return 0;
}

So here you need to explicitly type cast to derived class.

method((Bar*) obj1);

Hope this helps.

Upvotes: 1

Adi Levin
Adi Levin

Reputation: 5233

An explicit conversion can be necessary in order to resolve ambiguity, when more than one conversion can be applied implicitly:

#include <iostream>
using namespace std;

void f(double x) {
    cout << "Double\n";
}

void f(int x) {
    cout << "Integer\n";
}

struct C
{
    C(float x) { this->x = x; }
    operator int() { return (int)x; }
    operator double() { return (double)x; }
    float x;
};

int main(int argc, char* argv[]) 
{
    C c(1);
    f(c); // error C2668: 'f' : ambiguous call to overloaded function
    f(static_cast<double>(c)); // calls f(double)
    f(static_cast<int>(c)); // calls f(int)
}

Upvotes: 2

Related Questions