0

I have a class with overloaded operator=(const char&)

_obj operator=(const char& in){
    this->out = convert(in);
    return *this;
}

with 'this->out' being of class string

I can do:

_obj tmp;
tmp = 'c';

and program compiles and run as intended.

But when I do:

_obj tmp = 'c';

I get a compile error:

error: conversion from 'char' to non-scalar type '_obj' requested.

What exactly is the differens between these two statements?

First statement creates an object of type _obj with constructor _obj::_obj() with first line and use the overloaded operator=(const char&) to assign the char with the second line.

The second statement tries to directly convert a char to type of _obj, but why is that so, when there is a operator= telling what to do.

How would the class and operator would have to be formed to allow creation and assignment in a single line of code?

Thanks in advance

MJeB
  • 1
  • 1
    `_obj tmp = 'c';` requires a constructor accepting a `char`. – Jarod42 Apr 29 '15 at 11:52
  • I allready tried to give a constructor _obj::_obj(const char& in) but still got the compiler error – MJeB Apr 29 '15 at 12:45
  • My bad. I missed the simple word const in the constructor. Now it works as expected. I wonder why the compiler tried to convert from char to _obj instead of telling me of illegal conversion from const char to char. – MJeB Apr 29 '15 at 12:53

0 Answers0