assigning and object equivalent to object of same type with argument

Why can't I set and object without argument equivalent to another object of the same type with an argument. It compiles when I don't set the object on right side of equal sign a argument. The code commented out at the end of main compiles and runs. Why can I not say Cents cCentssum = cCentss2(8); Could you explain the details I know what will work but don't understand why. This routine is just and overloaded + routine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 // plusoperand.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
 
class Cents
{
	int m_nCents;
public:
		Cents(int nCents){m_nCents = nCents;}
	    friend Cents operator+(const Cents &c1,const Cents &c2);
		int GetCents(){return m_nCents;}
};

Cents operator+(const Cents &c1,const Cents &c2)
{
	return Cents(c1.m_nCents + c2.m_nCents);
}

int main()
{
	using namespace std;
	
	Cents cCentss1(6);
	Cents cCentss2(8);
	// Cents cCentsum = cCentss1 + cCentss2; this compiles and run
	// Cents cCentsum = cCentss2; this compiles and run
	Cents CCentsum = cCentss2(8); // this don't compile
	
         cout<<"I have "<<cCentsum.GetCents()<<" cents"<<endl;

	cin.clear();
         cin.ignore( 255,'\n');
	cin.get();
	return 0;
}
Instead of

Cents CCentsum = cCentss2(8);

you shold write

Cents CCentsum = Cents(8);

The statement

Cents CCentsum = cCentss2(8);

means that in your class there is defined a function call operator.

For example

1
2
3
4
5
6
7
8
9
class Cents
{
// other stuff

   Cents operator ()( int i ) const
   {
      return Cents( i );
   }
};
Topic archived. No new replies allowed.