0% found this document useful (0 votes)
5 views39 pages

C++ 090 Overloading

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views39 pages

C++ 090 Overloading

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Advanced Programming Techniques

Operator and Method Overloading


State_C ontrol
Signal_A dapter C
State_C ontrol_A UDI o
on_ select_prev () n
init() on_select_next() t
raise_tick() on_tick() on_select_next() r
raise_select_prev () on_triptime_alarm() on_tick() o
raise_select_next() 1 on_mem_lev el_dow n() on_triptime_alarm() l
raise_triptime_alarm() on_mem_lev el_up() on_ select_prev ()
raise_ignition_on() on_mem_lev el_dow n() S
on_ignition_on() e
raise_ignition_off() on_ignition_off() on_mem_lev el_up() c
raise_reset_program() on_reset_program() on_ignition_off() t
raise_reset_all_programs() on_reset_all_programs() on_ignition_on() i
raise_eeprom_changed() on_eeprom_changed() reset_program() o
raise_memlev el_down() reset_all_programs() n
<<ctor>> init()
raise_memlev el_up() Create()

Impl_Tripdistance_A UDI C
Impl_Tripdistance
Program a
Data_Adapter l
c
calc_v alue() : v oid u
display () : v oid Imp_Triptime_Alarm l
ignition_on() : v oid Impl_Triptime_A larm_A UDI a
ignition_off() : void t
i
reset() : v oid Impl_Triptime o
<<?>> eeprom_changed() : ... n
need_recalc() : bool
Impl_Mean_C onsumption_A U DI S
Impl_Mean_C onsumption e

Prof. Dr.-Ing. Peter Fromm


c
t
i
Impl_C urrent_C onsumption Impl_C urrent_C onsumption_AUDIo
n

Impl_Average_Speed

Prof. Dr.-Ing. Michael Lipp Display _A dapter

clear()
Impl_Range

write_str()
<<draft>> w rite_sy mbol()
<<ctor>> init()
D
i
s
Display _Triptime_A larm_A U DI p
Display_Triptime_A larm l
Display_V alue a
O SEK-VGC y
(from SYS) show(v alue : dword) : v oid Display _Mean_C onsumtion_A U DI
Display _Mean_C onsumption S
e
c
t
i
O SEK-win32 Display_C urrent_C onsumption_A U DIo
Display _C urrent_C onsumption
(from SYS) n

Display_Tripdistance Display_Tripdistance_A UDI


console-win32
(from SYS)

"classes " of lefthand coloumns in the middel build up the trip computer core. The classes on the right side all
coloumn act as inerface to A ll code has to be independent of manufacturer. belong to the A UDI package
hareware and O S. They and are not part of the main class
are declared abstract in the The Impl_XXX and Display_XXX classes describe what flav ours of program hierarchy.
main class hierarchy and functionality are expected
implemented in several They are included to show where
SYS packages. the main class hierarchy has to be
expanded for manufactorer's
requirements
Content

 Method Overloading
 Understand operator overloading

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 2
Wrap-Up

Class hierarchies
 Aggregation
 Composition
 Inheritance

Extended application of inheritance


 Multiple inheritance
 Abstract base class operations for interface design

Now it’s time to go for some real C++ features

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 3
C++ Name Spaces

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 4
Top level namespace

 Global names can lead to problems


 Two teams using something like “CDriver” (can partially be
overcome by strict naming rules)
 Third party code may use names that conflict with own company's
naming rules
 Solution: namespaces
 Names must only be unique within a single namespace
 So far we have used the “global namespace”

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 5
Definition and usage of namespace

 Definition
namespace myNameSpace {
// Declarations
}
 Using names from different namespaces
 Permanently
using namespace myNameSpace;
 Only for some names using namespace as prefix
myNameSpace::CCoordinate
 “using” shouldn't be used in header files because all files including
the header file will (involuntarily) be affected
 “using” may be used in a block (makes names available within
block)
 Explains “preamble” for using I/O streams
 cin, cout defined in namespace std

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 6
C++ Name Spaces

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 7
Extended CCoordinate Class

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 8
Extended Requirement 1 : Initialization

To facilitate the initialization of object, we want to support different


parameters for the constructor:

 CCoordinate(x,y)  Generate an object at position (x,y)


 CCoordinate(Q1|Q2|Q3|Q4)  Generate an object at (+/-1,+/-1)

Q2(-1,1) Q1(1,1)
x 1 x
x P(x,y)
1

x x
Q3(-1,-1) Q4(1,-1)

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 9
C++ Method Overloading

In C, a function is identified by it’s name alone.


 set(int x, int y)
 set(float w)
are identical and will generate a compiler error.

error C2084: function 'void set(int,int)' already has a body

This is a serious constraint especially for large software programs,


because the chance that 2 or more developers provide a function with
the same name is rather big.

Typical workarounds:
 Naming conventions
 Manual namespace (e.g. CComplex_set1, CComplex_set2)
  hard to maintain and difficult to use

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 10
C++ Method Overloading

C++ provides more levels of namespaces (i. e. parts of the qualifying


name)
 namespace
 class
 method name
 parameter set

namespace::class::method(parameterset)

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 11
C++ Method Overloading
Declaration
//Alternative parameter for initialization
enum t_quadrant{Q1, Q2, Q3, Q4};

//First Constructor for flexible coordinates


CCoordinate(float x = 0, float y = 0);

//Second Constructor for fixed positions


CCoordinate(t_quadrant quadrant);

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 12
C++ Method Overloading
Implementation
CCoordinate::CCoordinate(float x, float y)
{
m_x = x;
m_y = y;
cout << "Generated object at adress " << this <<" with the values: "
<< m_x << " , " << m_y << endl;
}

CCoordinate::CCoordinate(t_quadrant quadrant)
{
switch (quadrant)
{
case Q1: m_x = 1; m_y = 1; break;
case Q2: m_x = -1; m_y = 1; break;
case Q3: m_x = -1; m_y = -1; break;
case Q4: m_x = 1; m_y = -1; break;
}
cout << "Generated object at adress " << this <<" with the values: "
<< m_x << " , " << m_y << endl;
}

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 13
C++ Method Overloading
Call
//Old convention with default parameters
CCoordinate c1(2,2);
CCoordinate c2;
CCoordinate c4(5);

//Alternative constructor with quadrant type


CCoordinate c5(Q3);

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 14
C++ Method Overloading

In C++ you may overload


 all methods
 constructor
 almost all operations

 but not the destructor

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 15
C++ Operator Overloading

Let’s add two coordinates – the traditional solution

CCoordinate c1(3,4);
CCoordinate c2(4,5);
CCoordinate c3;

c3.add(c2,c2); //OK but not spectacular

The better solution (more intuitive) would be something like

c3 = c1+c2
../myCode/main.cpp:23:10: error: no match for ‘operator+’ in ‘c1 +
c2’
../myCode/main.cpp:23:10: note: candidates are:
/usr/include/c++/4.6/bits/stl_iterator.h:327:5: note:
template<class _Iterator> std::reverse_iterator<_Iterator>
std::operator+(typename
std::reverse_iterator<_Iterator>::difference_type, const
std::reverse_iterator<_Iterator>&)
Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 16
C++ Operator Overloading

The bad news:

 The Compiler doesn’t know how to add to CCoordinate Objects

The good news


 We can tell him how it works

The expected behavior:


 result = operant1 + operant2
 result.m_x = operant1.m_x + operant2.m_x
 result.m_y = operant1.m_y + operant2.m_y

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 17
C++ Operator Overloading
Declaration

//Overloaded + Operator for 2 CCoordinate Objects


friend CCoordinate operator+(const CCoordinate& c1, const CCoordinate& c2);

right operant

left operant

overwritten operator

return type

friend needed to access


private members

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 18
C++ Operator Overloading
Implementation
CCoordinate operator+(const CCoordinate& c1, const CCoordinate& c2)
{
CCoordinate result;
result.m_x = c1.m_x + c2.m_x;
result.m_y = c1.m_y + c2.m_y;
return result;
}

Implementation outside class


scope!

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 19
C++ Operator Overloading
Declaration

//Overloaded + Operator for 2 CCoordinate Objects


friend CCoordinate operator+(const CCoordinate& c1, const CCoordinate& c2);

right operant

left operant

overwritten operator

return type

friend needed to access


private members

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 20
C++ Operator Overloading
Alternative format – member function

//Overloaded + Operator for 2 CCoordinate Objects


CCoordinate operator+( const CCoordinate& c2);

right operant

overwritten operator

return type
Left operand: this pointer

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 21
C++ Operator Overloading

How about:

c6 = c1 + 4;

This will work on some compiler and is implemented as „binary“


operation  usually resulting in a wrong calculation.

 individual operator overloading needed for every parameter


combination!

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 22
C++ Operator Overloading

//+ with 2 CCoordinate objects


friend CCoordinate operator+(const CCoordinate& c1, const CCoordinate& c2);

//+ with CCoordinat and float


friend CCoordinate operator+(const CCoordinate& c1, float c2);

CCoordinate operator+(const CCoordinate& c1, const CCoordinate& c2)


{
CCoordinate result;
result.m_x = c1.m_x + c2.m_x;
result.m_y = c1.m_y + c2.m_y;
return result;
}

CCoordinate operator+(const CCoordinate& c1, float c2)


{
return CCoordinate(c1+CCoordinate(c2));
}

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 23
Combining Operator Overloading and
Namespace

 Operator may be overloaded within the classes namespace


namespace APT {
class CCoordinate {
// …
}
// The following declaration effectively overloads the
// operator+ in the namespace, it declares APT::operator+
CCoordinate operator+ (CCoordinate c1, Ccoordinate c2);
} // End namespace
 When using an operator, the compiler searches for overloaded
operators in the namespaces of the operands first, so our overloaded
operator is found
 When providing the definition, make sure to define
APT::operator+, not the global ::operator+

using namespace APT;


CCoordinate APT::operator+(CCoordinate c1, CCoordinate c2) {
// …
}

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 24
Rules for C++ Operator Overloading

 Implementation format is close to normal methods


 Usually implemented outside class scope
 friend keyword needed to allow access to private member variables
 Own implementation needed for every combination of parameter
types
 object,object
 int, object
 object, int
 float, object
 object, float
 …

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 25
List of overloadable binary operators

Binary:

 Convention: return_type operator@ (left_datatype, right_datatype)


 @ above stands for the operator to be overloaded.

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 26
Overloading using methods

 Overloading binary operators using functions is the most flexible


approach (free choice of operand types)
 If the type of the first operand is a class under developer's control,
overloading the operator can also be done by declaring a method

class CCoordinate { Implementation within class scope!


public:
operator+(const CCoordinate& rightOperand);
}

 When called, the left operand becomes the object the method is
invoked for, the right operand is passed as the parameter

c1 + c2 → c1.operator+(c2)

 This way of overloading is mandatory for overloading the assignment


operator (see following slide)
Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 27
Overloading using methods

 Overloading binary operators using functions is the most flexible


approach (free choice of operand types)
 If the type of the first operand is a class under developer's control,
overloading the operator can also be done by declaring a method

class CCoordinate { Implementation within class scope!


public:
operator+(const CCoordinate& rightOperand);
}

 When called, the left operand becomes the object the method is
invoked for, the right operand is passed as the parameter

c1 + c2 → c1.operator+(c2)

 This way of overloading is mandatory for overloading the assignment


operator (see following slide)
Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 28
Unary Operator

How about

CCoordinate c1(1,2);
c1++;

print(c1++)  c1 is printed and THEN incremented


print(++c1)  c1 is incremented and THEN printed

Needed for example


to build for loops with
the new class

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 29
Unary Operators
Example
public:
// Some unary operators - implemented as member, no friend needed
CCoordinate& operator++(); // Prefix increment operator.
CCoordinate operator++(int); // Postfix increment operator.

// Define prefix increment operator.


CCoordinate& CCoordinate::operator++()
{
++m_x;
m_y++; //Here, the order makes no difference
return *this; // Return value of current object
// dereferenced this pointer. Due to call by reference
// (&CCoordinate) the original object is overwritten
}

// Define postfix increment operator.


// No reference here, because of stack adress
CCoordinate CCoordinate::operator++(int)
{
CCoordinate temp = *this; // Content of the current object value
++*this; // Object is incremented
return temp; // Old value is returned

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 30
List of overloadable unary operators

Unary:

 Sender on the right: return_type operator@ ()


 When the sender is on the left: return_type operator@ (int)
 @ above stands for the operator to be overloaded.
 The int parameter essentially means nothing but is a convention for
the compiler to show that the sender is on the left of the operator.
 Implemented as class member

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 31
<< Operator

Almost perfect, the last requirement was to support something like

CCoordinate c1(3,4);
cout << c1 << endl;

For this, we have to override the << operator

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 32
<< Operator

//the << operator to support cout << CCoordinate


friend ostream& operator<<(ostream& out, const CCoordinate& c);

ostream& operator<<(ostream& out, const CCoordinate& c)


{
out << "(x,y) = (" << c.m_x << ", " << c.m_y << ")";
return out;
}

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 33
Overloading of operators and methods

Providing well designed overloaded methods and operators for your


class will significantly improve its usability in terms of

 completeness
 intuitive use

  colleagues will love to use your code!

the best documentation is the


one you don’t have to read

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 34
Operator overloading „must“

 In general operator overloading is an option


 Though overloading “<<” is a real nice to have
 Sometimes however, it is a “must” as far as the assignment operator
is concerned
 The default operation for an assignment generated by the compiler is
a bitwise copy of all attributes
 This causes problems when referencing resources, especially
dynamic memory
 References to dynamic memory stored in attributes of the target
object are lost (overwritten)
 Referenced resources (dynamic memory) is shared by the objects
after the assignment (shallow copy)
 Remember the matrix?

Life demo
Add assignment operator to CMatrix

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 35
Implementation of Copy Constructor and
Assignment Operator

Copy Constructor Assignment Operator

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 27/11/14 36
Copy constructor, destructor, assignment
operator

Rule

A class needs either no explicitly programmed


copy constructor, destructor and assignment operator
or it needs all three

Advanced Programming Techniques Prof. Dr.-Ing. P. Fromm, adapted by Prof. Dr.-Ing. M. Lipp 27/11/14 37
Wrap-Up

 Overloading operators is a must to improve usability and


completeness of your class
 Implementation is comparable to normal methods
 Parameter sets
 Return values
 Special conventions have to be considered for unary and <<
operators
 Special care has to be taken of the assignment operator

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 38
Proposal for own studies

Extend the operators for the coordinate class


 Minus
 Multiplication

Advanced Programming Techniques, Prof. Dr.-Ing. P. Fromm, Prof. Dr.-Ing. M. Lipp 27/11/14 39

You might also like