Classes

I've never started learning classes seriously so let's start:
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
using namespace std;

/* Class A: pointers and operator + returns *this */
class A
{
public:      
int i;  
A(int _i=5){i=_i;}          
A operator +(A b)
  {
   this->i=(this->i)+b.i;
   return *this;
  } 
};

/* Class B: almost the same as Class A */
class B
{
public:      
int i;  
B(int _i=5){i=_i;}          
B *operator +(B b)
  {
   this->i=(this->i)+b.i;
   return this;
  } 
};

/* Class C: passing by reference */
class C
{
public:      
int i;  
C(int _i=5){i=_i;}          
C &operator +(C b)
  {
   this->i=(this->i)+b.i;
   //return this;
  } 
};






int main()
{
A aa(15),ab(15);    
B ba(10),bb(9);
C ca(80),cb(20);


cout <<"Klase A:  aa=="<<aa.i<<"\t ab=="<<ab.i<<"\t aa+ab=="; aa+ab; cout <<aa.i<<endl;
cout <<"Klase B:  ba=="<<ba.i<<"\t bb=="<<bb.i<<"\t ba+bb=="; ba+bb; cout<<ba.i<<endl;
cout <<"Klase C:  ca=="<<ca.i<<"\t cb=="<<cb.i<<"\t ca+cb=="; ca+cb; cout<<ca.i<<endl;


getchar();

}

Questions:
1. Which one class should I use and why?
2. When I change
 
cout <<"Klase C:  ca=="<<ca.i<<"\t cb=="<<cb.i<<"\t ca+cb=="; ca+cb; cout<<ca.i<<endl

to
 
cout <<"Klase C:  ca=="<<ca.i<<"\t cb=="<<cb.i<<"\t ca+cb=="<<(ca+cb).i<<endl;

program crashes. Why?

Thanks for help.
1) None of them. All of them overload + incorrectly. Logically, + should not change the class.

When you do the following:

1
2
int a = 3;
int b = a + 5;


You don't expect 'a' to change. It should stay == 3.

Likewise if you do this with a class... the class should not change as a result of the addition.

The proper way to overload + would be as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
class D
{
public:      
  int i;  
  D(int _i=5){i=_i;}          
  D operator + (const D& b) const
  {
    D temp(*this);  // make a copy of this object
    temp.i += b.i;  // add 'b' to the temp object
    return temp;  // and return the temp object
  // note we never change 'this'
  }
};


2) I'm not sure why that would even compile, let alone crash. You can't add ca+cb.... the compiler should be giving you errors.
Last edited on
Topic archived. No new replies allowed.