when does the conversion take place??

i want to do a summation between an object and an integer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Base
{
	int x;
public:
	Base(int a) {x=a;}
	
	//operator int() {return x;}
};


void main (void)
{
	Base a(1);
	
	cout<<a+100<<endl;
	
	cout.flush();
	getchar();
}



if i dont have the line 7 i receive many errors
i thought that the constructor Base(int a) {x=a;} would be called for integer 100
but it doesnt
is there a general rule about when the constructor will be called and when a conversion operator is needed??
Last edited on
Did you define Base::operator+(const Base &) const ?

Now suppose that you have it, and the casting operator:
Base(42) + 100; What will happen? Who is going to be called plus<int> or plus<Base> ?
Last edited on
There is indeed a implicit conversion from int to Base due to your constructor.
So if you have a function like this
void f(Base b)
you can invoke it this way:
f(5)
which is esentially the same as:
f(Base(5))

But this only works if it's not ambiguous.
So if you have another function void f(SomeOtherClass) and there's also an constructor like in Base (i.e. one that can be used with a single int), the compiler doesn't know which function to use.

To "add" an instance of class Base and an integer you need to define either of these:
1
2
3
4
5
6
7
Base& Base::operator+(const Base&); // int is convertible to Base
Base& Base::operator+(int); // specifically adds an int
Base& Base::operator+(long int) ;  //also float, double since int is convertible to these
Base operator+(const Base&, int); // specifically adds Base and int
Base operator+(const Base&, const Base&); // adds to Base's but both can be int's (i.e. also works if the first operand is an int)
Base operator+(int, const Base&);
Base operator+(const Base&, int);

(plus you can exchange each const Base& argument with either const Base, Base& or Base)


Since you didn't provide any means to add a Base to something else this will be a compile time error. So define any of the ones above (or even all if you want to).

Besides, if you want to put an object of type Base in an outputstream like cout you need to define something like
 
std::ostream& operator<<(std::ostream& os, const Base& b);

(make it a friend of the base class or add some kind of accessor to the underlying int)

closed account (D80DSL3A)
Is cout<<a.x+100<<endl; missing the point somehow?
Last edited on
ok i understand you are corect
it doesnt exist an operator of + with the object
so it converts the object to integer and not the integer to object..

fun2code you are correct but i only do some experiments to learn how operators work..

thank you for the knowledge!!
Topic archived. No new replies allowed.