help with constructor and setter.

consider the following program:

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
#include<iostream>
using namespace std;

class variables {
      
     int m_number;
      
      public:
             
         variables(int num) { m_number = num; }
          int  Get_number() { return m_number;}
          
};

 variables Add(variables &c1,variables &c2) 
 
 { 
           return(c1.Get_number() + c2.Get_number());
           }


int main() {
    
    variables c1(5);
    
    variables c2(5);
    
  
    
    
    
    cout << Add(c1,c2).Get_number() << endl;
    
    cin.get();
    cin.get();
    return 0;
}


it works fine.But then consider the second one:

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
38
#include<iostream>
using namespace std;

class variables {
      
     int m_number;
      
      public:
             
          void Set_number(int num) { m_number = num; }
          int  Get_number() { return m_number;}
          
};

 variables Add(variables &c1,variables &c2) 
 
 { 
           return(c1.Get_number() + c2.Get_number());
           }


int main() {
    
    variables c1;
    
    c1.Set_number(5);
    
    variables c2;
    
    c2.Set_number(5);
    
  
    cout << Add(c1,c2).Get_number() << endl;
    
    cin.get();
    cin.get();
    return 0;
}


to be honest with you, I really need someone to make me understand why the second one does not work. The constructor and the setter does nearly the same thing right? so why is it that the first one work and second one don't? please explain like I'm five.Thank you.
In the first sample code there is a conversion constructor that accepts an argument of the type int. The second sample code has no such constructor. Your function Add in the return statement has the expression of the type int which shall be converted to the type variables because you specified such return type. But there is no such constructor in the second sample code. So the compiler shall issue an error.

so, the reason why there is an error is because the return type is simply different?
Because there is no conversion function that can convert from int to variables.
how will I write the 'conversion function' that can convert int to variables then?
closed account (zb0S216C)
He means there's no constructor that accepts an int argument in the 2nd variables class. The compiler will not generate one if you've forgotten.

Wazzak
Last edited on
Topic archived. No new replies allowed.