0% found this document useful (0 votes)
38 views

Chapter III. Object-Oriented Programming in C++

The document discusses object-oriented programming concepts in C++, including classes, objects, inheritance, and polymorphism. It begins with an introduction to object-oriented programming basics like classes, objects, methods, and message passing. It then covers key principles like encapsulation, inheritance, abstraction, and polymorphism. An example code is provided to demonstrate object-oriented programming in practice. The document also examines classes and objects in more detail, comparing structures to classes, and exploring constructors and destructors.

Uploaded by

Long
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)
38 views

Chapter III. Object-Oriented Programming in C++

The document discusses object-oriented programming concepts in C++, including classes, objects, inheritance, and polymorphism. It begins with an introduction to object-oriented programming basics like classes, objects, methods, and message passing. It then covers key principles like encapsulation, inheritance, abstraction, and polymorphism. An example code is provided to demonstrate object-oriented programming in practice. The document also examines classes and objects in more detail, comparing structures to classes, and exploring constructors and destructors.

Uploaded by

Long
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/ 165

TRƯỜNG ĐẠI HỌC BÁCH KHOA HÀ NỘI

KỸ THUẬT LẬP TRÌNH HỆ CƠ ĐIỆN TỬ


Programming Engineering in Mechatronics

Giảng viên: TS. Nguyễn Thành Hùng


Đơn vị: Bộ môn Cơ điện tử, Viện Cơ khí

Hà Nội, 2020 1
Chapter III. Object-oriented programming in C++

❖ Introduction to the object-oriented world


❖ Classes and objects
❖ Inheritance (derivation)
❖ Polymorphism
❖ Class templates

2
Chapter III. Object-oriented programming in C++

❖ Introduction to the object-oriented world


❖ Classes and objects
❖ Inheritance (derivation)
❖ Polymorphism
❖ Class templates

3
Introduction to the object-oriented world

❖ Basics
❖ Basic principles
❖ An object-oriented example code

4
Introduction to the object-oriented world

❖ Basics
▪ Class
• A class determines the abstract features of a object, including its
features (attributes, fields, properties) and its behaviour (what
the thing can do, methods, operations and functions).
• We can say that a class is a scheme describing the nature of
something.
• Both the integrated properties and the methods of a class are
called class members.

5
Introduction to the object-oriented world

❖ Basics
▪ Object
• An object is a scheme (an example) of a class.

▪ Instance
• Instance means an actual object created at runtime: myCar is an
instance of the class Truck.
• The set of the property values of the actual object is called
the state of that object.

6
Introduction to the object-oriented world

❖ Basics
▪ Method
• Methods are responsible for the capabilities of objects: the
methods of myCar: Brake(), Ignition(), ...
• In C++, methods are rather called member functions.

▪ Message passing
• Message passing is the process during which an object sends
data to another object or "asks" another object to execute one
of its methods.
• On the code level, message passing is realised by calling a
method in C++. 7
Introduction to the object-oriented world

❖ Basics
❖ Basic principles
❖ An object-oriented example code

8
Introduction to the object-oriented world

❖ Basic principles
▪ Encapsulation, data hiding
• Classes principally consist of features (state) and methods
(behaviour).
• There are some features and methods that we hide from other
objects. These are internal (private or protected) states and
behaviour.
• However, the others are made public.
• According to the basic principles of OOP, the state features have
to be private while most of the methods may be public.

9
Introduction to the object-oriented world

❖ Basic principles
▪ Inheritance
• Inheritance means creating specific versions of a class that inherit the
features and behaviour of their parent class (base class) and use them as if
they were of their own. The classes created in this way are called subclasses
or derived classes.

Inheritance 10
Introduction to the object-oriented world

❖ Basic principles
▪ Inheritance
• Actually, inheritance is an is-a relation: myCar is a HeavyTruck,
a HeavyTruck is a Truck. So myCar has the methods of both
HeavyTruck and Truck.
• Both derived classes have one direct parent class, namely Truck.
This inheritance method is called single inheritance.
• Multiple inheritance means that a derived class inherits the
members of more direct parent classes.

11
Introduction to the object-oriented world

❖ Basic principles
▪ Inheritance

Multiple inheritance

12
Introduction to the object-oriented world

❖ Basic principles
▪ Abstraction
• Abstraction simplifies complex reality by modelling problems
with their corresponding classes and it has its effects on the level
of inheritance appropriate for these problems.
• Abstraction can be achieved through composition.
• An interface determines how to send element or receive from
element messages and it gives information about the interaction
between the components of the class.

13
Introduction to the object-oriented world

❖ Basic principles
▪ Abstraction

14
Introduction to the object-oriented world

❖ Basic principles
▪ Polymorphism
• Polymorphism makes it possible to replace the content of some
inherited (deprecated) behaviour forms (methods) with a new
one in the derived class and to treat the new, replaced methods
as the members of the parent class.

15
Introduction to the object-oriented world

❖ Basics
❖ Basic principles
❖ An object-oriented example code

16
Introduction to the object-oriented world

❖ An object-oriented example code

17
Chapter III. Object-oriented programming in C++

❖ Introduction to the object-oriented world


❖ Classes and objects
❖ Inheritance (derivation)
❖ Polymorphism
❖ Class templates

18
Classes and objects

❖A class declaration has two parts:


➢ The header of the class contains the keyword class/struct,
followed by the name of the class.
➢ The class body is enclosed within curly brackets followed by a
semi-colon ➔ contain the data members, member functions, and
the keywords regulating access to the members and followed by a
colon: public, private (hidden) and protected.

19
Classes and objects

❖General form of a class:

20
Classes and objects

❖ From structures to classes


❖ More about classes
❖ Operator overloading

21
Classes and objects

❖ From structures to classes


▪ A little revision

22
Classes and objects

❖ From structures to classes


▪ Grouping together data and operations

23
Classes and objects

❖ From structures to classes


▪ Data hiding
• In object-oriented programming it is required that the data
members of classes could not be accessed directly from the
outside.
• The type struct offers complete access to its members by
default, whereas the class type completely hides its members
from the outside.
• The access of class elements can be defined by programmers as
well with the keywords private, protected and public.

24
Classes and objects

❖ From structures to classes


▪ Data hiding

25
Classes and objects

❖ From structures to classes


▪ Constructors
• A constructor is a member function the name of which
corresponds to the name of the class and has no return type.
• A constructor only has to initialise the memory space already
allocated for the object.
• A class has two constructors by default: a constructor without
parameters (default) and a copy constructor.

26
Classes and objects

❖ From structures to classes


▪ Constructors

27
Classes and objects

❖ From structures to classes


▪ Constructors

28
Classes and objects

❖ From structures to classes


▪ Constructors
• Constructors with and without parameters are often contracted
by introducing default arguments:

29
Classes and objects

❖ From structures to classes


▪ Constructors
• Using member initialisation lists

30
Classes and objects

❖ From structures to classes


▪ Constructors
• Explicit initialisation of objects

31
Classes and objects

❖ From structures to classes


▪ Destructor
• C++ offers a special member function, the destructor, in which
we can free the allocated resources.
• The name of a destructor has to be provided as a class name
with the tidle character (~).
• A destructor, just like constructors, does not return any value.

32
Classes and objects

❖ From structures to classes


▪ Destructor

33
Classes and objects

❖ From structures to classes


▪ Destructor
• If a destructor is not written for a class, the compiler
automatically adds an empty destructor for that class.

34
Classes and objects

❖ From structures to classes


▪ Objects of a class, the pointer this

The class Employee and its objects 35


Classes and objects

❖ From structures to classes


▪ Objects of a class, the pointer this
• Each member function has an invisible parameter (this) in which
a pointer to the actual object is passed to the function when it is
called.
• All references to data members are inserted in a program code
automatically in the following way:

36
Classes and objects

❖ From structures to classes


▪ Objects of a class, the pointer this
• Programmers may also use the pointer this within member
functions.

37
Classes and objects

❖ From structures to classes


❖ More about classes
❖ Operator overloading

38
Classes and objects

❖ More about classes


▪ Static class members
• A static data member that is created in only one instance belongs
directly to the class; therefore it is available for it even if there
are no objects for that class.
• A static data member should not be initialised within its class
(independently of its access restriction).
• If a static data member is public, then it can be used anywhere in
the program code by the name of the class and the scope
operator (::).

39
Classes and objects

❖ More about classes


▪ Static class members

40
Classes and objects

❖ More about classes


▪ Static class members

41
Classes and objects

❖ More about classes


▪ How to structure classes
• Implicit inline member functions

42
Classes and objects

❖ More about classes


▪ How to structure classes
• Class structures in C++/CLI applications

43
Classes and objects

❖ More about classes


▪ How to structure classes
• Storing member functions in separate modules

44
Classes and objects

❖ More about classes


▪ Friend functions and classes
• The friend mechanism makes it possible for us to access the
private and protected members of a class from a function
outside the class.

45
Classes and objects

❖ More about classes


▪ Friend functions and classes

46
Classes and objects

❖ More about classes


▪ What can we also add to classes?
• Constant data members of objects

47
Classes and objects

❖ More about classes


▪ What can we also add to classes?
• Reference type data members

48
Classes and objects

❖ More about classes


▪ What can we also add to classes?
• Data members as objects

49
Classes and objects

❖ More about classes


▪ What can we also add to classes?
• Pointers to class members
In order to define pointers correctly, we have to use the name of
the class and the scope operator:

class Class; forward class declaration,


p is a pointer to a data member of
int Class::*p;
type int,

pfunct may point to a member function


void
that is called with an argument of
(Class::*pf unct )(int);
type int and that returns no value.
50
Classes and objects

❖ More about classes


▪ What can we also add to classes?
• Pointers to class members

51
Classes and objects

❖ More about classes


▪ What can we also add to classes?
• Pointers to class members
By using typedef, expressions containing pointers are easier to
be handled:

52
Classes and objects

❖ From structures to classes


❖ More about classes
❖ Operator overloading

53
Classes and objects

❖ Operator overloading
• An operator function can be used if one of its parameters is a
class of type class or struct. General declaration of operator
functions:

Where the sequence op can be replaced by any of the following


operators:
[] () . -> ++ -- & new
* + - ~ ! / % new[]
<< >> < > <= >= == delete
!= ^ | && || = *= delete[]
/= %= += -= <<= >>= &=
^= |= , ->* 54
Classes and objects

❖ Operator overloading
• The following operators cannot be overloaded : member
selection (.), indirect member selection (.*), scope (::),
conditional (?:) and the operators sizeof and typeid since their
overloading would result in undesired side effects.
• The assignment (=), the "address of" (&) and the comma (,)
operations can be applied to objects without overloading.
• Overloading operators does not result in modifying the operator
precedence and associativity, and it is not possible to introduce
new operations.

55
Classes and objects

❖ Operator overloading
▪ Creating operator functions
Expression Operator( ♣ ) Member function External function
+-*&!~
♣a A::operator ♣ () operator ♣ (A)
++ --
a♣ ++ -- A::operator ♣ (int) operator ♣ (A, int)
+-*/%^&
a♣b | < > == != <= A::operator ♣ (B) operator ♣ (A, B)
>= << >> && || ,
= += -= *= /=
a♣b %= ^= &= |= <<= A::operator ♣ (B) -
>>= []
a(b, c...) () A::operator()(B, C...) -
a->b -> A::operator->() -
56
Classes and objects

❖ Operator overloading
▪ Creating operator functions
• The operators =, (), [] and -> can only be overloaded by non-
static member functions.
• The operators new and delete are overloaded with static
member functions.
• All other operator functions can be created as member functions
or external (in general friend) functions.

57
Classes and objects

❖ Operator overloading
▪ Creating operator functions
• Binary operands:

Realisation Syntax Actual call


member function X op Y X.operator op(Y)
external function X op Y operator op(X,Y)

58
Classes and objects

❖ Operator overloading
▪ Creating operator functions
• Unary operands:

Realisation Syntax Actual call


member function op X X.operator op()
member function X op X.operator op(0)
external function op X operator op(X)
external function X op operator op(X,0)

59
Classes and objects

❖ Operator overloading
▪ Creating operator functions

60
Classes and objects

❖ Operator overloading
▪ Creating operator functions

61
Classes and objects

❖ Operator overloading
▪ Creating operator functions

62
Classes and objects

❖ Operator overloading
▪ Using type conversion operator functions

63
Classes and objects

❖ Operator overloading
▪ Using type conversion operator functions

64
Classes and objects

❖ Operator overloading
▪ Extending classes with input/output operations
• To "teach" I/O data streams based on classes to handle the
objects of user-defined classes.

65
Classes and objects

❖ Operator overloading
▪ Extending classes with input/output operations

66
Classes and objects

❖ Operator overloading
▪ Extending classes with input/output operations

67
Chapter III. Object-oriented programming in C++

❖ Introduction to the object-oriented world


❖ Classes and objects
❖ Inheritance (derivation)
❖ Polymorphism
❖ Class templates

68
Inheritance (derivation)

• Inheritance makes it possible to create (to derive) new classes


from already existing ones.
• Derivation means that a new class inherits the public and
protected properties (data members) and behaviour (member
functions) of already existing classes and it then uses them as its
own.

69
Inheritance (derivation)

• However:
➢ already existing classes may be extended with a new class,
➢ new data members and member functions may be defined
➢ or inherited member functions may be reinterpreted (replaced) if
they become deprecated concerning their functioning
(polymorphism).

70
Inheritance (derivation)

• class A, that is derived or from which


members are inherited: base class , ancestor
class , parent class, superclass
• the operation: inheritance , derivation ,
extending, subclassing
• class B, the result of derivation: descendant
class, derived class, extended class, child
class, subclass

71
Inheritance (derivation)

The C++ program code that realises the relation


above:

class ClassA {
// ...
};

class ClassB : public ClassA {


// ...
};

72
Inheritance (derivation)

The multiple inheritance of I/O classes in C++

73
Inheritance (derivation)

Hierarchy of geometrical classes


74
Inheritance (derivation)

❖ Derivation of classes
❖ Initialising base class(es)
❖ Accessing class members in case of inheritance
❖ Virtual base classes in case of multiple inheritance
❖ Inheritance and/or composition?

75
Inheritance (derivation)

❖ Derivation of classes
• A derived (descendant) class is a class that inherits its data
members and member functions from one or more already
defined class(es).
• The class from which a derived class inherits is called base class
(ancestor class).
• A derived class inherits all the members of its base class;
however, it only have access to the public and protected
members of its base class as its own.

76
Inheritance (derivation)

❖ Derivation of classes
• The place where a derivation is indicated in a program code is
the class header where the mode of derivation (public,
protected, private) is indicated before the names of base classes:

77
Inheritance (derivation)

❖ Derivation of classes

78
Inheritance (derivation)

❖ Derivation of classes

79
Inheritance (derivation)

❖ Derivation of classes
• The keywords public, protected and private used in a derivation
list restrict the access of inherited (public and protected)
members in their new classes:

Mode of inheritance Access in the base class Access in the derived class
public public
public
protected protected

public protected
protected
protected protected

public private
private
protected private

80
Inheritance (derivation)

❖ Derivation of classes
• The access of any member (the access type of which is protected
or public in the base class) can be manually set directly.

81
Inheritance (derivation)

❖ Derivation of classes
❖ Initialising base class(es)
❖ Accessing class members in case of inheritance
❖ Virtual base classes in case of multiple inheritance
❖ Inheritance and/or composition?

82
Inheritance (derivation)

❖ Initialising base class(es)


• In order that base class(es) be initialised, it is the extended
version of member initialisation lists that is used.

83
Inheritance (derivation)

❖ Derivation of classes
❖ Initialising base class(es)
❖ Accessing class members in case of inheritance
❖ Virtual base classes in case of multiple inheritance
❖ Inheritance and/or composition?

84
Inheritance (derivation)

❖ Accessing class members in case of inheritance


▪ Accessing inherited members

85
Inheritance (derivation)

❖ Accessing class members in case of inheritance


▪ Accessing inherited members

The members of the base The members of the derived class


class Point2D: Point3D
protected: x, y protected: x, y, z
public: Point2D(), public: Point3D(int…),
Point3D(Point3D&…),
GetPoint2D(), Move(int…),
Move(const…), PrintOut() GetPoint2D(),Point2D()::Move(int…),
Point2D()::Move(const…),
Point2D()::PrintOut(), GetPoint3D(),
Move(int…), Move(const…), PrintOut()
86
Inheritance (derivation)

❖ Accessing class members in case of inheritance


▪ The friend relationship in inheritance
• In a derived class, a friend of the base class can only access the
members inherited from the base class.
• A "friend" of a derived class can only access public and
protected members from the base class.

87
Inheritance (derivation)

❖ Derivation of classes
❖ Initialising base class(es)
❖ Accessing class members in case of inheritance
❖ Virtual base classes in case of multiple inheritance
❖ Inheritance and/or composition?

88
Inheritance (derivation)

❖ Virtual base classes in case of multiple inheritance


• In case of multiple inheritance, it may be a problem if the same
base class appears as many instances in the derived class.
• If virtual base classes are used, problems of that type can be
avoided.

89
Inheritance (derivation)

❖ Virtual base classes in case of multiple inheritance

Using virtual base classes 90


Inheritance (derivation)

❖ Virtual base classes in case of multiple inheritance

91
Inheritance (derivation)

❖ Virtual base classes in case of multiple inheritance

92
Inheritance (derivation)

❖ Derivation of classes
❖ Initialising base class(es)
❖ Accessing class members in case of inheritance
❖ Virtual base classes in case of multiple inheritance
❖ Inheritance and/or composition?

93
Inheritance (derivation)

❖ Inheritance and/or composition?


• A big advantage of C++ programming language is that it supports
the reusability of program code.
• Reusing means that a new program code is made without
modifying the original one.

94
Inheritance (derivation)

❖ Inheritance and/or composition?


• If the object-oriented tools of C++ are used, there are three
approaches to choose from:
➢ The most simple and frequent reuse of a code stored in a given
class is when an object instance is created or when already
existing objects (cin , cout , string , STL etc.) are used in a
program.

95
Inheritance (derivation)

❖ Inheritance and/or composition?


➢ Another possibility is to place objects of other classes in our own
codes as member objects ➔ This method is called composition.
If the new object will only contain a pointer or a reference to
other objects, it is called an aggregation.

96
Inheritance (derivation)

❖ Inheritance and/or composition?


➢ The third solution: when a new class is created by public
derivation from other classes, then the relationship is of an is-
a type ➔ a derived object behaves exactly the same way as its
ancestor class.

97
Inheritance (derivation)

❖ Inheritance and/or composition?

98
Inheritance (derivation)

❖ Inheritance and/or composition?


▪ Reuse with composition

99
Inheritance (derivation)

❖ Inheritance and/or composition?


▪ Reuse by public inheritance

100
Chapter III. Object-oriented programming in C++

❖ Introduction to the object-oriented world


❖ Classes and objects
❖ Inheritance (derivation)
❖ Polymorphism
❖ Class templates

101
Polymorphism

In C++, polymorphism rather means that the object of a derived


class is accessed by a pointer or a reference in the base class.

• Coercion polymorphism means implicit and explicit type casts.


➢ In that case, the polymorphism of a given operation is made
possible by different types that may be converted if needed.

• As an opposite to coercion, the so-called ad-hoc (“for that


purpose”) polymorphism is better known by the name of
function overloading.
➢ In that case, a compiler chooses the appropriate function from
the variants on the basis of parameter types.
102
Polymorphism

• The extended version of this polymorphism is called parametrical


or compile-time polymorphism, which makes it possible to execute
the same code with any type.
➢ In C++, parametric polymorphism is realised by function and
class templates. Using templates actually means reusing a C++
source code.

103
Polymorphism

❖ Virtual member functions


❖ Redefining virtual functions
❖ Early and late binding
❖ Virtual destructors
❖ Abstract classes and interfaces
❖ Run-time type informations in case of classes

104
Polymorphism

❖ Virtual member functions


• A virtual function is a public or protected member function of
the base class.
• It can be redefined in the derived class in order that the behavior
of the class would change.
• A virtual function is generally called by a reference or a pointer
of a public base class, the actual value of which is determined at
run-time (dynamic binding, late binding).
• Declaration of the virtual function:

105
Polymorphism

❖ Virtual member functions


• It is not necessary that a virtual function in the base class have a
definition as well.
• Instead, the prototype of the function should be ended with the
expression = 0; .
• In that case, it is a so-called pure virtual function:

106
Polymorphism

❖ Virtual member functions


❖ Redefining virtual functions
❖ Early and late binding
❖ Virtual destructors
❖ Abstract classes and interfaces
❖ Run-time type informations in case of classes

107
Polymorphism

❖ Redefining virtual functions

108
Polymorphism

❖ Redefining virtual functions

109
Polymorphism

❖ Redefining virtual functions

110
Polymorphism

❖ Redefining virtual functions


• Virtual functions and public inheritance make it possible to create
external functions that can be called by every object in the class
hierarchy:

111
Polymorphism

❖ Virtual member functions


❖ Redefining virtual functions
❖ Early and late binding
❖ Virtual destructors
❖ Abstract classes and interfaces
❖ Run-time type informations in case of classes

112
Polymorphism

❖ Early and late binding


▪ Static early binding
• During early binding, compilers integrate statically direct
member function calls into the code.

Early binding example

113
Polymorphism

❖ Early and late binding


▪ Static early binding

114
Polymorphism

❖ Early and late binding


▪ Dynamic late binding

Late binding example

115
Polymorphism

❖ Early and late binding


▪ Dynamic late binding

116
Polymorphism

❖ Early and late binding


▪ Virtual method table
• In case a class has one or more virtual member functions,
compilers complete the object with a "virtual pointer" to the
global data table called virtual method table (VMT) or virtual
function table (VFTable).
• VMT contains function pointers to the virtual member functions
redefined the last of the given class and the base classes.
• VMTs for classes are created at run-time when the first
constructor is called.

117
Polymorphism

❖ Early and late binding


▪ Virtual method table

Virtual method tables of the example code 118


Polymorphism

❖ Virtual member functions


❖ Redefining virtual functions
❖ Early and late binding
❖ Virtual destructors
❖ Abstract classes and interfaces
❖ Run-time type informations in case of classes

119
Polymorphism

❖ Virtual destructors

120
Polymorphism

❖ Virtual member functions


❖ Redefining virtual functions
❖ Early and late binding
❖ Virtual destructors
❖ Abstract classes and interfaces
❖ Run-time type informations in case of classes

121
Polymorphism

❖ Abstract classes and interfaces

122
Polymorphism

❖ Abstract classes and interfaces

123
Polymorphism

❖ Virtual member functions


❖ Redefining virtual functions
❖ Early and late binding
❖ Virtual destructors
❖ Abstract classes and interfaces
❖ Run-time type informations in case of classes

124
Polymorphism

❖ Run-time type informations in case of classes

125
Polymorphism

❖ Run-time type informations in case of classes

126
Polymorphism

❖ Run-time type informations in case of classes

127
Polymorphism

❖ Run-time type informations in case of classes

128
Polymorphism

❖ Run-time type informations in case of classes


• The version of the code above that does not use run-time type
information

129
Polymorphism

❖ Run-time type informations in case of classes


• Result

130
Chapter III. Object-oriented programming in C++

❖ Introduction to the object-oriented world


❖ Classes and objects
❖ Inheritance (derivation)
❖ Polymorphism
❖ Class templates

131
Class templates

❖ A step-be-step tutorial for creating and using class templates


❖ Defining a generic class
❖ Instantiation and specialisation
❖ Value parameters and default template parameters
❖ The "friends" and static data members of a class template
❖ The Standard Template Library (STL) of C++

132
Class templates

❖ A step-be-step tutorial for creating and using class templates


• A simplified class handling an one-dimensional integer array of
32 elements with bound index checking

133
Class templates

❖ A step-be-step tutorial for creating and using class templates


• A class template

134
Class templates

❖ A step-be-step tutorial for creating and using class templates


• In the case of external member functions, the name of the class
has to be used together with the generic type and the parameter
Array<type, numberOfElements>:

135
Class templates

❖ A step-be-step tutorial for creating and using class templates


• let's see how a class template can help us

• The template created from that can be used also for storing
character sequences and objects.

136
Class templates

❖ A step-be-step tutorial for creating and using class templates


137
Class templates

❖ A step-be-step tutorial for creating and using class templates


❖ Defining a generic class
❖ Instantiation and specialisation
❖ Value parameters and default template parameters
❖ The "friends" and static data members of a class template
❖ The Standard Template Library (STL) of C++

138
Class templates

❖ Defining a generic class


• A parametrized or generic class makes it possible for us to use
the parametrized class as a template to create new classes.
➢ So a given class definition can be used for all types.

139
Class templates

❖ Defining a generic class


• The non-inline member functions of the class should be defined
as follows:

140
Class templates

❖ Defining a generic class

141
Class templates

❖ Defining a generic class


• The same Point class becomes much more complicated if one
part of its member functions is defined outside the class:

142
Class templates

❖ A step-be-step tutorial for creating and using class templates


❖ Defining a generic class
❖ Instantiation and specialisation
❖ Value parameters and default template parameters
❖ The "friends" and static data members of a class template
❖ The Standard Template Library (STL) of C++

143
Class templates

❖ Instantiation and specialisation


• A template can be defined in many ways.
➢ In implicit instantiation, type parameters are replaced by
concrete types. First the version of the given type of a class is
created (if it has not yet been created), then the object instance:

144
Class templates

❖ Instantiation and specialisation


• In explicit instantiation, the compiler is asked to create an
instance of the class by using the given types, so when the object
is being created, the class is ready to be used:

145
Class templates

❖ Instantiation and specialisation


• Among the following declarations:
➢ the first one is a general template,
➢ the second one is a version
tailored to pointers,
➢ the third is a version specialised
to void* pointers.

146
Class templates

❖ Instantiation and specialisation

147
Class templates

❖ Instantiation and specialisation

148
Class templates

❖ A step-be-step tutorial for creating and using class templates


❖ Defining a generic class
❖ Instantiation and specialisation
❖ Value parameters and default template parameters
❖ The "friends" and static data members of a class template
❖ The Standard Template Library (STL) of C++

149
Class templates

❖ Value parameters and default template parameters


• C++ supports default template parameters.

150
Class templates

❖ Value parameters and default template parameters


• Example

151
Class templates

❖ Value parameters and default template parameters


• Example

152
Class templates

❖ A step-be-step tutorial for creating and using class templates


❖ Defining a generic class
❖ Instantiation and specialisation
❖ Value parameters and default template parameters
❖ The "friends" and static data members of a class template
❖ The Standard Template Library (STL) of C++

153
Class templates

❖ The "friends" and static data members of a class template


• A class template may also have friends, which may behave
differently.

154
Class templates

❖ The "friends" and static data members of a class template

155
Class templates

❖ The "friends" and static data members of a class template

156
Class templates

❖ A step-be-step tutorial for creating and using class templates


❖ Defining a generic class
❖ Instantiation and specialisation
❖ Value parameters and default template parameters
❖ The "friends" and static data members of a class template
❖ The Standard Template Library (STL) of C++

157
Class templates

❖ The Standard Template Library (STL) of C++


▪ The structure of STL
The elements of the Library can be grouped into five groups:
• containers – data structures making it possible to store data in
memory (vector, list, map, set, deque, …)
• adaptors – higher-level data structures based on containers
(stack, queue, priority_queue)
• algorithms - operations that can be carried out on data stored in
containers (sort, copy, search, min, max, …)

158
Class templates

❖ The Standard Template Library (STL) of C++


▪ The structure of STL
The elements of the Library can be grouped into five groups:
• iterators – generic pointers that ensure access to the data stored
in containers (iterator, const_iterator, ostream_iterator<>, … )
• function objects – functions are covered by classes, for other
components (divides, greater_equal, logical_and, …).

159
Class templates

❖ The Standard Template Library (STL) of C++


▪ The structure of STL
Short description Header file
Managing, sorting data in containers and searching in them <algorithm>
Associative container for storing bits: bitset <bitset>
Associative containers that store elements: multiset (may have the same
<set>
elements more times), and set (stores only unique elements)
Associative container storing key/value pairs in a 1:1 relation (map), or in a
<map>
1:n relation (multiset)
Predefined iterators, datastream iterators <iterator>
Container: dynamic array <vector>
Container: double ended queue <deque>
Container: linear list <list>
Container adaptor: queue <queue>
Container adaptor: stack <stack> 160
Class templates

❖ The Standard Template Library (STL) of C++


▪ STL and C++ arrays

161
Class templates

❖ The Standard Template Library (STL) of C++


▪ STL and C++ arrays

162
Class templates

❖ The Standard Template Library (STL) of C++


▪ Using STL containers

163
Class templates

❖ The Standard Template Library (STL) of C++


▪ Using STL container adaptors
• The adapted stack functions are summarised in the following
table:
void push(const value_type& a) inserting in the stack,
void pop() removing the top element of the stack,
value_type& top() accessing the top element of the stack,
const value_type& top() const accessing the top element of the stack,
bool empty() const returns true, if the stack is empty,
size_type size()const the number of elements in the stack,
the operations "equals" and "smaller
operator== and operator<
than".
164
Class templates

❖ The Standard Template Library (STL) of C++


▪ Using STL container adaptors

165

You might also like