0

My question is regarding data type conversion in c++. Does c++ provides a implicit conversion for built-in data types ( int, float) to user defined data types?

In the following example, I am trying to add a double ( t4 = t3 + 1.0) with test object type and its working fine using + operator so is the double implicitly converted to test type object?

class test {
    double d;
    int m;

    public:
    test() {
        d=0;
        m=0;
    }

    test(double n) {
        d=n;
    }

    const test operator+(const test& t) {
        test temp;
        temp.d = d+ t.d;
        return temp;
    }
};

int main() {
    test t1(1.2);
    test t2(2.5);
    test t3, t4;
    t3= t1+ t2;
    t4 = t3 + 1.0;
    return 0;
}
1
  • 4
    This code does not compile, because your class test does not have any constructor, yet you call one in test t1(1.2). Please post real code. Commented Dec 20, 2011 at 7:35

2 Answers 2

1

The constructor test(double n) declares an implicit conversion from double to test. In general, any constructor that is callable with exactly one argument (that includes constructors that can take more arguments, but have default-values for those), can be used as an implicit conversion, unless it is marked explicit:

struct Foo {
    Foo(int x); // implicit conversion from int to Foo
    explicit Foo(char c); // marked explicit - no implicit conversion
    Foo(std::string a, double pi = 3.14159); // can be used as implicit 
                                             // conversion due to default 
                                             // argument
};

Edit: t4 = 1.0 + t3 does not work, because you have overloaded your operator+ as a member-function, and thus it is only considered if the first operand is of the type test - implicit conversion are not tried in this case. To make this work, make your operator a free function:

test operator+(const test& lhs, const test& rhs);
Sign up to request clarification or add additional context in comments.

2 Comments

ok.. but then why t4 = 1.0 + t3 doesn't work? shouldn't it be converted implicitly like: t4 = test(1.0) + t3;
Edited my answer to explain that.
0

Yes, as long as your constructor test(double) is not explicit

// implicite convertible
test(double n)
{
  d=n;
}

// not implicite convertible
explicit test(double n)
{
  d=n;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.