-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathObjectOrientedProgrammingDefiningClasses.ptx
More file actions
1029 lines (931 loc) · 48.3 KB
/
ObjectOrientedProgrammingDefiningClasses.ptx
File metadata and controls
1029 lines (931 loc) · 48.3 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<section xml:id="introduction_object-oriented-programming-in-c-defining-classes">
<title>Object-Oriented Programming in C++: Defining Classes</title>
<introduction>
<p><idx>object-oriented programming</idx>We stated earlier that C++ is an <term>object-oriented programming
language</term>. Object-oriented programming is a programming technique based on
real world things such as turtles, airplanes, customers, etc.
Each object has its own characteristics or attributes as well as its own set of behaviors.</p>
<p><idx>object</idx><idx>instance</idx>So far, we have used a number of built-in classes to show
examples of data and control structures. One of the most powerful
features in an object-oriented programming language is the ability to
allow a programmer (problem solver) to create new classes that model
data that is needed to solve the problem.
Each <term>object</term> created with the class data type is called an <term>instance</term> of the class.</p>
<p><idx>object attributes</idx><idx>class methods</idx><idx>class</idx>Remember that we use abstract data types to provide the logical
description or blueprint for what a data object looks like (its state given by <term>object attributes</term>)
and what it can do (its behaviors given by <term>class methods</term>).
Defining a class creates the blueprint which defines the behaviors and attributes
of objects of that new data type.
By building a <term>class</term> that implements an abstract data
type, a programmer can take advantage of the abstraction process and at
the same time provide the details necessary to actually use the
abstraction in a program. Hence, whenever we want to implement an abstract data
type, we will do so with a new class which will provide the blueprint or template for
all of the objects of that type.</p>
<p>Four key principles are associated with object-oriented programming:</p>
<blockquote>
<p><ol marker="1">
<li>
<p>abstraction</p>
</li>
<li>
<p>encapsulation</p>
</li>
<li>
<p>inheritance</p>
</li>
<li>
<p>polymorphism</p>
</li>
</ol></p>
</blockquote>
<p>We will highlight each principle via examples.</p>
</introduction>
<subsection xml:id="introduction_a-fraction-class">
<title>A <c>Fraction</c> Class</title>
<p>A very common example to show the details of implementing a user-defined
class is to construct a class to implement the abstract data type
<c>Fraction</c>. We have already seen that C++ provides a number of
numeric data types for our use. There are times, however, that it would be
most appropriate to be able to create data objects that both look and act like
fractions.</p>
<p>A fraction such as <m>\frac {3}{5}</m> consists of two parts. The top
value, known as the numerator, can be any integer. The bottom value,
called the denominator, can be any integer greater than 0 (negative
fractions have a negative numerator). Although it is possible to create
a floating point approximation for any fraction, we would
like to represent the fraction using exact values to avoid problems inherent
in approximations.</p>
<p>Since defining a class makes a new data type, the operations for the
<c>Fraction</c> type will allow a <c>Fraction</c> data
object to behave like any other numeric type. We need to be able to
add, subtract, multiply, and divide fractions. We also want to be able
to print fractions using the standard <q>slash</q> form, for example 3/5. In
addition, all fraction methods should return results in their lowest
terms so that no matter what computation is performed, we always end up
with the most common form.</p>
<p>In C++, we define a new class by providing a name and a set of method
definitions that are syntactically similar to function definitions.
For example, see <xref ref="defn-classes"/>.</p>
<exploration xml:id="defn-classes">
<title>Defining Classes</title>
<task xml:id="defn-classes-cpp" label="defn-classes-cpp">
<title>C++ Implementation</title>
<statement><program language="cpp" label="defn-classes-cpp-prog"><input>
class Fraction {
// The class methods and class variables go here
}; // The ";" is required by C++ to end a class definition
</input></program></statement>
</task>
<task xml:id="defn-classes-py" label="defn-classes-py">
<title>Python Implementation</title>
<statement><program language="python" label="defn-classes-py-prog"><input>
class Fraction:
#the methods go here
</input></program></statement>
</task>
</exploration>
<p><idx>constructor</idx>provides the framework for us to define the methods. The first method
that all classes should provide is the <term>constructor</term>.
The constructor
defines the way in which data objects are created.
It's considered good practice to have a constructor completely setup a class object,
so that it's impossible to create an object in an invalid state.
To create a
<c>Fraction</c> object, we will need to initialize two pieces of data, the
numerator and the denominator. In C++, the constructor method is
always named with the same name as the class it creates
and is shown in <xref ref="introduction_lst-constructor-cpp"/>.</p>
<exploration xml:id="introduction_lst-constructor">
<title>Constructor for <c>Fraction</c> class</title>
<task xml:id="introduction_lst-constructor-cpp" label="introduction_lst-constructor-cpp">
<title>C++</title>
<statement><program language="cpp" label="introduction_lst-constructor-cpp-prog"><input>
class Fraction {
public:
Fraction(int top, int bottom) {
/** Fraction constructor method */
num = top; // setting num's value
den = bottom; // setting den's value
}
private:
int num; // num attribute
int den; // den attribute
};
</input></program></statement></task>
<task xml:id="introduction_lst-constructor-py" label="introduction_lst-constructor-py">
<title>Python</title>
<statement><program language="Python" label="introduction_lst-constructor-py-prog"><input>
class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom
</input></program></statement></task></exploration>
<p>As described earlier, fractions require
two pieces of state data, the numerator and the denominator. The
notation <c>int num</c> outside the constructor defines the <c>fraction</c> object
to have an internal data object called <c>num</c> as part of its state.
Likewise, <c>int den</c> creates the denominator. The values of the two
formal parameters are initially assigned to the state, allowing the new
<c>fraction</c> object to know its starting values.</p>
<p>To create an object or instance of the <c>Fraction</c> class, we must invoke the
constructor. This happens by using the name of the class and passing
actual values for the necessary state after the variable name.
For example, see <xref ref="invoking-constructor"/>.</p>
<exploration xml:id="invoking-constructor">
<title>Invoking Constructor</title>
<task xml:id="invoking-constructor-cpp" label="invoking-constructor-cpp">
<title>C++ Implementation</title>
<statement><program language="cpp" label="invoking-constructor-cpp-prog"><input>
Fraction myfraction(3, 5);
</input></program></statement>
</task>
<task xml:id="invoking-constructor-py" label="invoking-constructor-py">
<title>Python Implementation</title>
<statement><program language="python" label="invoking-constructor-py-prog"><input>
myfraction = Fraction(3, 5)
</input></program></statement>
</task>
</exploration>
<p>creates an object called <c>myfraction</c> representing the fraction
<m>\frac {3}{5}</m> (three-fifths). <xref ref="fig-fraction1cpp"/> shows this
object as it is now implemented.</p>
<figure align="center" xml:id="fig-fraction1cpp">
<caption>An instance of the <c>Fraction</c> Class</caption>
<image source="Introduction/fraction1cpp.png" width="50%">
<description><p>Diagram showing an instance of the Fraction class. The instance is named 'myfraction' and is depicted as a set of concentric circles. The innermost circle is labeled 'State' and contains two segments: 'num' with the number 3 above 'den' with the number 5, representing the numerator and denominator of a fraction. The middle circle is labeled 'Methods', indicating the functionality associated with the fraction instance.</p></description>
</image>
</figure>
</subsection>
<subsection xml:id="introduction_abstraction-and-encapsulation">
<title>Abstraction and Encapsulation</title>
<p>Another way to think about fractions is as <q>parts of a whole</q> as shown in the
following figure:</p>
<blockquote>
<image source="Introduction/fractions_partsofwhole.png" width="50%">
<description>
<p>
Image showing a visual representation of fractions as "parts of a whole." The diagram begins with a full circle labeled "1,"
followed by a circle divided into two equal parts labeled "1/2," then into four parts labeled "1/4," and finally into
eight parts labeled "1/8." The sequence visually illustrates how a whole can be divided into progressively smaller fractions.
</p>
</description>
</image>
</blockquote>
<p><idx>abstraction</idx>Because we are using classes to create abstract data types, we should probably
define the term <q>abstract</q> in this context. In object-oriented programming,
<term>abstraction</term> requires you to focus solely on the desired properties and behaviors of
the objects, discarding everything else that is unimportant or irrelevant. As a result,
if we don't need to consider the <q>parts of a whole</q> visual metaphor of a fraction, we won't include it in the
<c>Fraction</c> class. If a given metaphor is important, we will include it. For our purposes, we want to
think of fractions as numbers, so we will avoid using the <q>parts of a whole</q> visual
metaphor.</p>
<p><idx>access keywords</idx><idx>encapsulation</idx>The object-oriented principle of <term>encapsulation</term>
refers to the practice of grouping or encapsulating related data and the methods that operate on that data into a single unit, typically a class. Encapsulation also requires we hide most of the internal contents of that class, except what is
absolutely necessary to expose.
Hence, we will restrict the access to our class as much
as we can, so that a user can change the class properties and behaviors only from methods
provided by the class. C++ allows us to control access with the <term>access keywords</term> <c>public</c> and <c>private</c>.
It is typical in C++ to make all data attributes <c>private</c> and most methods <c>public</c>.
All attribute variables under the <c>private</c>
keyword will only be able to be accessed by the object's class methods, not by the user.
Only C++<rsq/>s <c>public</c> methods can be accessed and used by the user. Because we
want our user to be able to call every constructor directly, we always place the
constructor under <c>public</c>. A third access keyword, <c>protected</c> will be discussed later.</p>
</subsection>
<subsection xml:id="introduction_polymorphism">
<title>Polymorphism</title>
<p><idx>polymorphism</idx><term>Polymorphism</term> means the ability to appear in many forms. In object-oriented programming,
<term>polymorphism</term> refers to the ability to handle objects or methods differently depending
on their data type, class, number of arguments, etc.
For example, we can overload a constructor with different numbers and types of arguments
to give us multiple ways to instantiate an object of a class as shown in <xref ref="frac-poly"/> for
the <c>Fraction</c> class.</p>
<listing xml:id="frac-poly">
<caption>Example of Polymorphism</caption>
<program language="cpp" label="frac-poly-prog"><input>
Fraction(int top, int bottom){
num = top;
den = bottom;
}
Fraction (int top){
num = top;
den = 1;
}
Fraction (){
num = 0;
den = 1;
}
</input></program></listing>
<p>Calling the constructor with two arguments will invoke the first method,
calling it with a single argument will invoke the second method, and calling
it with no arguments will invoke the third method.</p>
<p>Using optional parameters will accomplish the same task in this case.
Since the class will behave the same no matter which implementation
you use and the user will have no idea which implementation was chosen,
this is an example of encapsulation.</p>
<pre>Fraction(int top = 0, int bottom = 1){
num = top;
den = bottom;
}</pre>
<p>The next thing we need to do is implement some behaviors that the abstract
data type requires. To begin, let's consider what happens when we try to print
a <c>Fraction</c> object.</p>
<program language="cpp" label="ObjectOrientedProgrammingDefiningClasses-prog">int main() {
Fraction myfraction(3, 5);
// Throws an error
cout << myfraction << endl;
return 0;
}</program>
<p>The <c>fraction</c> object, <c>myfraction</c>, does not know how to respond to this
request to print to the console. The <c>cout</c> function requires that the object
knows how to interact with the <c><<</c> operator so that the string can be sent to the
output stream. Without this, our class will throw an error, which is obviously not what we
want.</p>
<p>There are two ways we can solve this problem. One is to define a method
called something like <c>show</c> that will allow the <c>Fraction</c> object to print itself
as a string. We can implement this method as shown in
<xref ref="showmethod-cpp"/>. If we create a <c>Fraction</c> object as before, we
can ask it to show itself, in other words, print itself in the proper
format by invoking the show method on our fractions.</p>
<exploration>
<title>Implementing a <c>show</c> method</title>
<task xml:id="showmethod-cpp" label="showmethod-cpp">
<title>C++</title>
<statement><program interactive="activecode" language="cpp" label="showmethod-cpp-prog"><input>
//using functions to print fractions to the command line.
#include <iostream>
using namespace std;
class Fraction {
public:
Fraction(int top = 0, int bottom = 1){
num = top;
den = bottom;
}
void show(){
cout << num << "/" << den << endl;
}
private:
int num, den;
};
int main() {
Fraction fraca(3, 5);
Fraction fracb(3);
Fraction fracc; //notice there are no parentheses here.
// cout << fraca << endl; //uncomment to see error
fraca.show();
fracb.show();
fracc.show();
return 0;
}
</input></program></statement>
</task>
<task xml:id="showmethod-py" label="showmethod_py">
<title>Python</title>
<statement><program interactive="activecode" language="python" label="showmethod_py-prog"><input>
class Fraction:
def __init__(self,top = 0,bottom = 1):
self.num = top
self.den = bottom
def show(self):
print(self.num,"/",self.den)
# main code below
fraca = Fraction(3,5)
fracb = Fraction(3)
fracc = Fraction()# notice no parameters are passed
# notice print(fraca) will give you an unexpected output
fraca.show()
fracb.show()
fracc.show()
</input></program></statement>
</task>
</exploration>
<p>The downside of this approach is that it is not how we expect to print to the console.
In C++, there are many operators that are provided for atomic and STL data types
that may not work as expected with a user defined class until you <term>overload</term> them.
One of these, <c><<</c>, is the operator to
send data to the output stream.
It would be nicer to provide a <q>better</q> implementation for this method
via operator overloading.</p>
<p><idx>operator overloading</idx>Like function overloading, <term>operator overloading</term> allows us to make operators
work for user defined classes
by defining a special meaning for that operator when applied to objects
of the class as operands.
This is a form of polymorphism because it enables the same operator to have
different behaviors depending on the class of the objects involved, demonstrating
how the same operation can be adapted to various types.</p>
<p><idx>friend</idx>In C++ this new operator needs to be implemented as a <term>friend</term> of the class in order to
define the operator's behavior on objects of the class from a non-class method <c><<</c>.
Operator overloading is yet another example
of polymorphism in object-oriented programming.</p>
<p><idx>friend function</idx>A <term>friend function</term> of a class is a function defined outside that class' scope
but with the right to access
all private and protected members of the class.
In C++, we overload an operator by declaring it a <term>friend</term>
function in the class definition and giving it a new implementation.
<xref ref="expl-overload"/> shows an example of the <c><<</c> operator being overloaded
in the <c>Fraction</c> class.
Note that stream operators
need to return the address of the stream because of the fact that the
stream is changed by the stream operator.</p>
<exploration xml:id="expl-overload">
<title>Operator Overloading Example</title>
<task xml:id="overloaded-cpp" label="overloaded-cpp">
<title>C++ Implementation</title>
<statement><program xml:id="overloaded_cpp" interactive="activecode" language="cpp" label="overloaded_cpp-prog"><input>
/*overloading functions to take in different
inputs and output the correct results*/
#include <iostream>
using namespace std;
class Fraction {
public:
Fraction(int top = 0, int bottom = 1){
num = top;
den = bottom;
}
//the following tells the compiler to look for this friend's definition outside the class
friend ostream &operator << (ostream &stream, const Fraction &frac);
private:
int num, den;
};
ostream &operator << (ostream &stream, const Fraction &frac) {
/** this is the definition. */
stream << frac.num << "/" << frac.den;
return stream;
}
int main() {
Fraction myfraction(3, 5);
cout << myfraction << " is my fraction" << endl;
return 0;
}
</input></program></statement>
</task>
<task xml:id="overloaded-py" label="overloaded-py">
<title>Python Implementation</title>
<statement><program language="python" label="overloaded-py-prog"><input>
def __str__(self):
return str(self.num)+"/"+str(self.den)
myf = Fraction(3,5)
print(myf)
print("I ate", myf, "of the pizza")
</input></program></statement>
</task>
</exploration>
<p>We can overload many other operators for our new <c>Fraction</c> class. Some
of the most important of these are the basic arithmetic operations. We
would like to be able to create two <c>Fraction</c> objects and then be able to add
them together using the standard <q>+</q> notation. At this point, if we try
to add two fractions using <q>+</q>, we get the following:</p>
<exploration xml:id="expl-adderror">
<title>Error Before Overloading Addition</title>
<task xml:id="adderror-cpp" label="adderror-cpp">
<title>C++ Addition Error</title>
<statement><console><input prompt="">
Fraction f1(1, 4);
Fraction f2(1, 2);
Fraction f3 = f1 + f2;
</input><output>
>> error: no match for `operator+' (operand types are `Fraction' and `Fraction'))
</output></console></statement>
</task>
<task xml:id="adderror-py" label="adderror-py">
<title>Python Addition Error</title>
<statement><console><input prompt="">
f1 = Fraction(1,4)
f2 = Fraction(1,2)
f1+f2
</input><output>
Traceback (most recent call last):
File "<pyshell#173>", line 1, in -toplevel- f1+f2
TypeError: unsupported operand type(s) for +: 'instance' and 'instance'
</output></console></statement>
</task>
</exploration>
<p>If you look closely at the error, you see that the problem is that the
<q>+</q> operator does not understand the <c>Fraction</c> operands.</p>
<p>We can, of course create something like <xref ref="expl-addmodel"/>.</p>
<exploration xml:id="expl-addmodel">
<title>Function for Addition</title>
<task xml:id="addmodel-cpp" label="addmodel-cpp">
<title>C++</title>
<statement><program language="cpp" label="addmodel-cpp-prog"><input>
f1.add(f2)
</input></program></statement>
</task>
<task xml:id="addmodel-py" label="addmodel-py">
<title>Python</title>
<statement><program language="python" label="addmodel-py-prog"><input>
f1.__add__(f2)
</input></program></statement>
</task>
</exploration>
<p>which would ask the <c>Fraction</c> object <c>f1</c> to add the <c>Fraction</c> object
<c>f2</c> to itself. It would be much better to be written in the standard notation,
<c>f1 + f2</c>. We can fix this by providing the <c>Fraction</c> class with a friend that
overloads the <c>+</c> operator.</p>
<p>As you know, two fractions must have the same denominator to be added. The easiest
way to make sure they have the same denominator is to simply use the
product of the two denominators as a common denominator so that
<m>\frac {a}{b} + \frac {c}{d} = \frac {ad}{bd} + \frac {cb}{bd} = \frac{ad+cb}{bd}</m>
The implementation is shown in <xref ref="introduction_lst-addmethod-cpp"/>. The addition
function returns a new <c>Fraction</c> object with the numerator and
denominator of the sum. We can use this method by writing a standard
arithmetic expression involving fractions, assigning the result of the
addition, and then printing our result.</p>
<exploration xml:id="expl-lst-addmethod">
<title>Adding an addition method</title>
<task xml:id="introduction_lst-addmethod-cpp" label="introduction_lst-addmethod-cpp">
<title>C++ Implementation</title>
<statement><program language="cpp" label="introduction_lst-addmethod-cpp-prog"><input>
Fraction operator +(const Fraction &otherFrac){
//Note the return type is a Fraction
int newnum = num*otherFrac.den + den*otherFrac.num;
int newden = den*otherFrac.den;
return Fraction(newnum, newden);
}
</input></program></statement>
</task>
<task xml:id="introduction_lst-addmethod-py" label="introduction_lst-addmethod-py">
<title>Python Implementation</title>
<statement><program language="python" label="introduction_lst-addmethod-py-prog"><input>
def __add__(self, otherfraction):
newnum = self.num*otherfraction.den + self.den*otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum,newden)
</input></program></statement>
</task>
<task xml:id="introduction_lst-addmethod-cpp-usage" label="introduction_lst-addmethod-cpp-usage">
<title>C++ Usage Example</title>
<statement><program xml:id="addfrac_cpp" label="addfrac_cpp" language="cpp" interactive="activecode"><input>
//using functions to abstract the idea of a fraction
#include <iostream>
using namespace std;
class Fraction {
public:
Fraction(int top = 0, int bottom = 1) {
num = top;
den = bottom;
}
Fraction operator +(const Fraction &otherFrac) {
int newnum = otherFrac.num*den + otherFrac.den*num;
int newden = den*otherFrac.den;
return Fraction(newnum, newden);
}
friend ostream &operator << (ostream &stream, const Fraction &frac);
private:
int num, den;
};
ostream &operator << (ostream &stream, const Fraction &frac) {
stream << frac.num << "/" << frac.den;
return stream;
}
int main(){
Fraction f1(1, 4);
Fraction f2(1, 2);
Fraction f3 = f1 + f2;
cout << f3 << " is "<< f1 << " + " << f2 << endl;
return 0;
}
</input></program></statement>
</task>
<task xml:id="introduction_lst-addmethod-py-usage" label="introduction_lst-addmethod-py-usage">
<title>Python Usage Example</title>
<statement><program xml:id="addfrac_py" label="addfrac_py" language="python" interactive="activecode"><input>
f1=Fraction(1,4)
f2=Fraction(1,2)
f3=f1+f2
print(f3)
</input></program></statement>
</task>
</exploration>
<p>The addition method works as we desire, but a couple of things
can be improved. When we use a binary operator like <c>+</c>, we
like more symmetry.
Binary operators can either be members of their
left-hand argument's class or friend functions.
Since the stream operators' left-hand argument is a stream,
stream operators (such as <c><<</c> and <c>>></c>) must be either member functions of the stream class
or friend functions of the class they are used with.
However, that is not true for the <c>+</c> operator.
Let's rewrite the addition operator as a friend function.</p>
<exploration xml:id="expl-addoverload">
<title>Overloading Addition</title>
<task xml:id="addoverload-cpp" label="addoverload-cpp">
<title>C++ Implementation</title>
<statement><program language="cpp" label="addoverload-cpp-prog"><input>
Fraction operator +(const Fraction &frac1, const Fraction &frac2) {
int newnum = frac1.num * frac2.den + frac1.den * frac2.num;
int newden = frac1.den * frac2.den;
return Fraction(newnum, newden);
}
</input></program></statement>
</task>
<task xml:id="addoverload-py" label="addoverload-py">
<title>Python Implementation</title>
<statement><program language="python" label="addoverload-py-prog"><input>
def __add__(self,otherfraction):
newnum = self.num*otherfraction.den + self.den*otherfraction.num
newden = self.den * otherfraction.den
return Fraction(newnum,newden)
</input></program></statement>
</task>
<task xml:id="addoverload-usage" label="addoverload-usage">
<title>C++ Usage</title>
<statement><program interactive="activecode" language="cpp" label="addoverload-usage-prog"><input>
//overloading the addition operator to create clearer syntax
#include <iostream>
using namespace std;
class Fraction {
public:
Fraction(int top = 0, int bottom = 1) {
num = top;
den = bottom;
}
friend ostream &operator << (ostream &stream, const Fraction &frac);
friend Fraction operator +(const Fraction &frac1, const Fraction &frac2);
private:
int num, den;
};
ostream &operator << (ostream &stream, const Fraction &frac) {
stream << frac.num << "/" << frac.den;
return stream;
}
Fraction operator +(const Fraction &frac1, const Fraction &frac2) {
int newnum = frac1.num * frac2.den + frac1.den * frac2.num;
int newden = frac1.den * frac2.den;
return Fraction(newnum, newden);
}
int main(){
Fraction f1(1, 4);
Fraction f2(1, 2);
Fraction f3 = f1 + f2;
cout << f3 << " is "<< f1 << " + " << f2 << endl;
return 0;
}
</input></program></statement>
</task>
</exploration>
<p>How you choose to overload operators like <c>+</c> is a design choice
since both methods will work perfectly well. This is another
example of encapsulation; your user does not need to know
which you choose to use!</p>
<p>There is one more thing we can improve in our addition function.
Note that <m>6/8</m> is the correct result
(<m>\frac {1}{4} + \frac {1}{2}</m>) but that it is not in the
<q>lowest terms</q> representation. The best representation would be
<m>3/4</m>. In order to be sure that our results are always in the
lowest terms, we need a helper function that knows how to reduce
fractions. This function will need to look for the greatest common
divisor, or GCD. We can then divide the numerator and the denominator by
the GCD and the result will be reduced to lowest terms.</p>
<p>The best-known algorithm for finding a greatest common divisor is
Euclid's Algorithm, which will be discussed in detail in <xref ref="ch-trees"/>.
Euclid's Algorithm states that the greatest common divisor of two
integers <m>m</m> and <m>n</m> is <m>n</m> if <m>n</m>
divides <m>m</m> evenly. However, if <m>n</m> does not divide
<m>m</m> evenly, then the answer is the greatest common divisor of
<m>n</m> and the remainder of <m>m</m> divided by <m>n</m>. We
will simply provide an iterative implementation here (see
<inline classes="xref std std-ref">ActiveCode 1</inline>). Note that this implementation of the GCD algorithm only
works when the denominator is positive. This is acceptable for our
fraction class because we have said that a negative fraction will be
represented by a negative numerator.</p>
<exploration xml:id="gcdalg">
<title>Greatest Common Divisor</title>
<task xml:id="gcd-cpp" label="gcd-cpp">
<title>C++ Implementation</title>
<statement><program interactive="activecode" language="cpp" label="gcd-cpp-prog"><input>
#include <iostream>
using namespace std;
int gcd(int m, int n) {
while (m%n != 0) {
int oldm = m;
int oldn = n;
m = oldn;
n = oldm%oldn;
}
return n;
}
int main() {
cout << gcd(20, 10) << endl;
return 0;
}
</input></program></statement>
</task>
<task xml:id="gcd-py" label="gcd-py">
<title>Python Implementation</title>
<statement><program interactive="activecode" language="python" label="gcd-py-prog"><input>
def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
print(gcd(20,10))
</input></program></statement>
</task>
</exploration>
<p>Now we can use this function to help reduce any fraction. To put a
fraction in lowest terms, we will divide the numerator and the
denominator by their greatest common divisor. So, for the fraction
<m>6/8</m>, the greatest common divisor is 2. Dividing the top and
the bottom by 2 creates a new fraction, <m>3/4</m> (see
<xref ref="introduction_lst-newaddmethod"/>).</p>
<listing xml:id="introduction_lst-newaddmethod">
<caption>New addition implementation using <c>gcd</c></caption>
<program xml:id="gcdadd" label="gcdadd" interactive="activecode" language="cpp"><input>
#include <iostream>
using namespace std;
int gcd(int m, int n){
/** gcd is a helper function, used by but not part of the Fraction class */
while (m%n != 0) {
int oldm = m;
int oldn = n;
m = oldn;
n = oldm%oldn;
}
return n;
}
class Fraction {
public:
Fraction(int top, int bottom) {
num = top;
den = bottom;
}
Fraction(int top){
num = top;
den = 1;
}
Fraction(){
num = 1;
den = 1;
}
Fraction operator +(const Fraction &otherFrac) {
int newnum = num*otherFrac.den + den*otherFrac.num;
int newden = den*otherFrac.den;
int common = gcd(newnum, newden);
return Fraction(newnum/common, newden/common);
}
friend ostream& operator << (ostream& stream, const Fraction& fraction);
private:
int num, den;
};
ostream & operator << (ostream& stream, const Fraction& fraction) {
stream<<fraction.num<<"/"<<fraction.den;
return stream;
}
int main(){
Fraction f1(1, 4);
Fraction f2(1, 2);
Fraction f3 = f1 + f2;
cout << f3 << " is "<< f1 << " + " << f2 << endl;
return 0;
}
</input></program>
</listing>
<figure align="center" xml:id="fig-fraction2cpp">
<caption>An Instance of the <c>Fraction</c> Class with Two Methods</caption>
<image source="Introduction/fraction2cpp.png" width="50%">
<description><p>Visual representation of a Fraction class instance called 'myfraction'. It features concentric circles with the innermost labeled 'State' showcasing 'num' with a value of 3 above 'den' with a value of 5, indicating the fraction's numerator and denominator. The outer circle is labeled 'Methods', suggesting the object's functionality. Two symbols, '<<' and '+', are shown outside the Methods circle, implying additional methods.</p></description>
</image>
</figure>
<p>Our <c>Fraction</c> object now has two very useful methods and looks
like <xref ref="fig-fraction2cpp"/>. An additional group of methods that we need to
include in our example <c>Fraction</c> class will allow two fractions to
compare themselves to one another using <c>==</c>.</p>
<p>We want the <c>==</c> operator to compare Fraction objects and to return
<c>true</c> if they are equivalent in value, <c>false</c> otherwise.
This is a design choice because we want <m>\frac {1}{2}</m> to be considered
equal to <m>\frac {2}{4}</m> as well as <m>\frac {3}{6}</m>, etc.
Hence, in the <c>Fraction</c> class, we can implement the <c>==</c> method by
cross-multiplying (see <xref ref="introduction_lst-cmpmethod-cpp"/>) rather than
by just comparing numerators and denominators.</p>
<p>Of course there are other relational operators that can be overridden. For example, the
<c><=</c> operator could be overridden to provide the less than or equal functionality.</p>
<exploration xml:id="introduction_lst-cmpmethod">
<title>Overloading the comparison operator</title>
<task xml:id="introduction_lst-cmpmethod-cpp" label="introduction_lst-cmpmethod-cpp">
<title>C++</title>
<statement><program language="cpp" label="introduction_lst-cmpmethod-cpp-prog"><input>
bool operator ==(const Fraction &otherFrac) {
int firstnum = num*otherFrac.den;
int secondnum = otherFrac.num*den;
return firstnum==secondnum;
}
</input></program></statement>
</task>
<task label="introduction_lst-cmpmethod-py">
<title>Python</title>
<statement><program language="python" label="introduction_lst-cmpmethod-py-prog"><input>
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
</input></program></statement>
</task>
</exploration>
<p>The complete <c>Fraction</c> class, up to this point, is shown in
<xref ref="fraction_class_cpp"/>. We leave the remaining arithmetic and relational
methods as exercises.</p>
<exploration xml:id="fraction_class">
<title>Complete <c>Fraction</c> class</title>
<task xml:id="fraction_class_cpp" label="fraction_class_cpp">
<title>C++</title>
<statement><program interactive="activecode" language="cpp" label="fraction_class_cpp-prog"><input>
#include <iostream>
using namespace std;
int gcd(int m, int n) {
while (m%n != 0) {
int oldm = m;
int oldn = n;
m = oldn;
n = oldm%oldn;
}
return n;
}
class Fraction {
public:
Fraction(int top, int bottom) {
num = top;
den = bottom;
}
Fraction(int top){
num = top;
den = 1;
}
Fraction(){
num = 1;
den = 1;
}
Fraction operator +(const Fraction &otherFrac) {
int newnum = num*otherFrac.den + den*otherFrac.num;
int newden = den*otherFrac.den;
int common = gcd(newnum, newden);
return Fraction(newnum/common,newden/common);
}
bool operator ==(const Fraction &otherFrac) {
int firstnum = num*otherFrac.den;
int secondnum = otherFrac.num*den;
return firstnum==secondnum;
}
friend ostream& operator<<(ostream& stream, const Fraction& fraction);
private:
int num, den;
};
ostream& operator << (ostream& stream, const Fraction& fraction) {
stream << fraction.num << "/" << fraction.den;
return stream;
}
int main(){
Fraction x(1, 2);
Fraction y(2, 4);
cout << x << " + " << y << " = " << x+y << endl;
if (x==y){
cout << "x is equal y" << endl;
}
else{
cout << "x is not equal y" << endl;
}
return 0;
}
</input></program></statement>
</task>
<task label="fraction_class_py">
<title>Python</title>
<statement><program xml:id="fraction_class_py" interactive="activecode" language="python" label="fraction_class_py-prog"><input>
def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num)+"/"+str(self.den)
def show(self):
print(self.num,"/",self.den)
def __add__(self,otherfraction):
newnum = self.num*otherfraction.den + \
self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
x = Fraction(1,2)
y = Fraction(2,3)
print(x + y)
print(x == y)
</input></program></statement></task>
</exploration>>
</subsection>
<subsection xml:id="introduction_self-check">
<title>Self-Check</title>
<p>To make sure you understand how operators are implemented in C++ classes, and how to properly write methods, write some methods to implement
<c>*</c>, <c>/</c>, and <c>-</c>. Also implement comparison operators <c>></c> and <c><</c>.</p>
<program xml:id="self_check_4cpp" interactive="activecode" language="cpp" label="self_check_4cpp-prog">
<input>
#include <iostream>
using namespace std;
int gcd(int m, int n) {
while (m%n != 0) {
int oldm = m;
int oldn = n;
m = oldn;
n = oldm%oldn;
}
return n;
}
class Fraction {
public:
Fraction(int top, int bottom) {
num = top;
den = bottom;
}
Fraction(int top){
num = top;
den = 1;
}
Fraction(){
num = 1;
den = 1;
}
Fraction operator +(const Fraction &otherFrac) {
int newnum = num*otherFrac.den + den*otherFrac.num;
int newden = den*otherFrac.den;
int common = gcd(newnum, newden);
return Fraction(newnum/common,newden/common);
}
bool operator ==(const Fraction &otherFrac) {
int firstnum = num*otherFrac.den;
int secondnum = otherFrac.num*den;
return firstnum==secondnum;
}
friend ostream& operator<<(ostream& stream, const Fraction& fraction);
private:
int num, den;
};
ostream& operator << (ostream& stream, const Fraction& fraction) {
stream << fraction.num << "/" << fraction.den;
return stream;
}
int main(){
Fraction x(1, 2);
Fraction y(2, 4);
cout << x << " + " << y << " = " << x+y << endl;
if (x==y){
cout << "x is equal y" << endl;
}
else{
cout << "x is not equal y" << endl;
}
return 0;
}
</input>
</program>
<p>Our the next section will introduce another important aspect of
object-oriented programming, namely <term>inheritance</term>.</p>
<reading-questions xml:id="rq-oop">
<title>Reading Questions</title>
<exercise label="aande">
<statement><p>Match the corresponding key word to the appropriate scenario.</p></statement>
<feedback><p>Review the definitions of the key words.</p></feedback>
<matches><match order="1"><premise>Encapsulation</premise><response>A situation where bank software programmers want to protect users' personal information.</response></match><match order="2"><premise>Abstraction</premise><response>A situation where software programmers want to develop similar objects without having to redefine the most similar properties.</response></match></matches></exercise>
<exercise label="class_syntax">
<statement><p>Click on the line where there is a syntax error when defining the following class</p></statement>
<feedback><p>C++ class definitions end with a certain symbol</p></feedback>
<areas>
<cline><area correct="no">class Fraction {</area></cline>
<cline> <area correct="no">public:</area></cline>
<cline> <area correct="no">Fraction(int top, int bottom) {</area></cline>
<cline> <area correct="no">/** Fraction constructor method */</area></cline>