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

Algorithm Programming: Object Oriented Programming

This document outlines a lecture on Object Oriented Programming in C++, covering key concepts such as classes and objects, inheritance, overloading, polymorphism, data abstraction, encapsulation, and interfaces. It provides detailed explanations of class definitions, member functions, access modifiers, constructors, destructors, and friend functions, along with homework assignments for practical application. The document serves as a comprehensive guide for students in a Mechatronics study program to understand and implement C++ programming principles.

Uploaded by

Hanny Berchmans
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)
8 views

Algorithm Programming: Object Oriented Programming

This document outlines a lecture on Object Oriented Programming in C++, covering key concepts such as classes and objects, inheritance, overloading, polymorphism, data abstraction, encapsulation, and interfaces. It provides detailed explanations of class definitions, member functions, access modifiers, constructors, destructors, and friend functions, along with homework assignments for practical application. The document serves as a comprehensive guide for students in a Mechatronics study program to understand and implement C++ programming principles.

Uploaded by

Hanny Berchmans
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/ 70

MECHATRONICS STUDY PROGRAM

ALGORITHM & PROGRAMMING


LECTURE 5:
(Object Oriented Programming: C++ Classes and Objects, Inheritance
Overloading (Operator and Function), Polymorphism in C++, Data
Abstraction in C++, Data Encapsulation in C++, Interfaces in C++ )

Dr. Ir. Hanny J. Berchmans, M.T., M.Sc.


Saturday, 9 May 2015
MECHATRONICS STUDY PROGRAM

OUTLINE

C++ Classes and Objects:


 Class Definitions, Define C++ Objects, Accessing the Data Members &
 Classes & Objects in Detail
Inheritance
Overloading (Operator and Function)
Polymorphism in C++
 Abstraction
Encapsulation
Interfaces
Classes and
MECHATRONICS STUDY PROGRAM Objects
Classes and Objects (1)

• The main purpose of C++ programming is to add object


orientation to the C programming language.
• Classes are the central feature of C++ that supports object-
oriented programming and are often called user-defined
types.

• A class is used to specify the form of an object and it


combines data representation and methods for
manipulating that data into one neat package. The data and
functions within a class are called members of the class.
Classes and
MECHATRONICS STUDY PROGRAM Objects
Classes and Objects (2)
C++ Class Definitions:
• When you define a class, you define a blueprint for a data type. This doesn't
actually define any data, but it does define what the class name means, that is,
what an object of the class will consist of and what operations can be performed
on such an object.
• A class definition starts with the keyword class followed by the class name; and
the class body, enclosed by a pair of curly braces. A class definition must be
followed either by a semicolon or a list of declarations. For example, we defined
the Box data type using the keyword class as follows:

• The keyword public determines the access attributes of the members of the class
that follow it. A public member can be accessed from outside the class anywhere
within the scope of the class object. You can also specify the members of a class
as private or protected which we will discuss in a sub-section.
Classes and
MECHATRONICS STUDY PROGRAM Objects
Classes and Objects (3)
Define C++ Objects:
• A class provides the blueprints for objects, so basically an object is
created from a class. We declare objects of a class with exactly the same
sort of declaration that we declare variables of basic types. Following
statements declare two objects of class Box:

• Both of the objects Box1 and Box2 will have their own copy of data
members.
Classes and
MECHATRONICS STUDY PROGRAM Objects
Classes and Objects (5)
Accessing the Data Members:
• The public data members of objects of a class can be accessed
using the direct member access operator (.). Let us try the
following example to make the things clear:

• See and Run Program_1.cpp

• When the above code is compiled and executed, it produces the


following result:

• It is important to note that private and protected members can not


be accessed directly using direct member access operator (.). We
will learn how private and protected members can be accessed.
Classes and
MECHATRONICS STUDY PROGRAM Objects
Classes & Objects in Detail:
• So far, you have got very basic idea about C++ Classes and Objects. There are further
interesting concepts related to C++ Classes and Objects which we will discuss in
various sub-sections listed below: .
Classes and
MECHATRONICS STUDY PROGRAM Objects
Class member functions (1)
• A member function of a class is a function that has its definition or its
prototype within the class definition like any other variable. It operates on
any object of the class of which it is a member, and has access to all the
members of a class for that object.
• Let us take previously defined class to access the members of the class
using a member function instead of directly accessing them:

• Member functions can be defined within the class definition or separately using
scope resolution operator, ::. Defining a member function within the class
definition declares the function inline, even if you do not use the inline specifier.
So either you can define Volume() function as below:
Classes and
MECHATRONICS STUDY PROGRAM Objects
Class member functions (2)

• If you like you can define same function outside the class using scope
resolution operator, :: as follows:

• Here, only important point is that you would have to use class name just before ::
operator. A member function will be called using a dot operator (.) on a object
where it will manipulate data related to that object only as follows:

• Let us put above concepts to set and get the value of different class members in a
class: See and Run Program_2.cpp
Homework
MECHATRONICS STUDY PROGRAM

A. Develop Class of: B. Develope Functions for the Class above:


1. Cube 1. Volume
2. Cylinder 2. Volume
3. Ball 3. Volume
4. Cone 4. Volume
5. Ellips 5. Area
6. Octahedron 6. Area
7. Limas 7. Area
8. Quadratic Equation 8. Roots Of Equation
9. Temperature 9. Conversion from C to F, Rankine, and Kelvin
10.Matrix with n=2 10. Invers and Determinant
11.Matrix with n=3 11. Invers and Determinant
12.Matrix with n=4 12. Invers
13.Matrix with n=5 13. Invers
Classes and
MECHATRONICS STUDY PROGRAM Objects
Class access modifiers (1)
• Data hiding is one of the important features of Object Oriented Programming which allows
preventing the functions of a program to access directly the internal representation of a
class type. The access restriction to the class members is specified by the labeled public,
private, and protected sections within the class body. The keywords public, private, and
protected are called access specifiers.
• A class can have multiple public, protected, or private labeled sections. Each section
remains in effect until either another section label or the closing right brace of the class
body is seen. The default access for members and classes is private.
Classes and
MECHATRONICS STUDY PROGRAM Objects
Class access modifiers (2)
The public members:
• A public member is accessible from anywhere outside the class but within a
program. You can set and get the value of public variables without any member
function as shown in the following example:
• See and Run Program_3.cpp and the result is :

The private members:


• A private member variable or function cannot be accessed, or even viewed
from outside the class. Only the class and friend functions can access private
members.
• By default all the members of a class would be private, for example in the
following class width is a private member, which means until you label a
member, it will be assumed a private member:
Classes and
MECHATRONICS STUDY PROGRAM Objects
Class access modifiers (3)
The private members:
• Practically, we define data in private section and related functions in public
section so that they can be called from outside of the class as shown in the
following program.

• See and Run Program_4.cpp and the result is :


Classes and
MECHATRONICS STUDY PROGRAM Objects
Class access modifiers (4)
The protected members:
• A protected member variable or function is very similar to a private member but it
provided one additional benefit that they can be accessed in child classes which are
called derived classes.
• You will learn derived classes and inheritance in next chapter. For now you can check
following example where I have derived one child class SmallBox from a parent class
Box.
• Following example is similar to above example and here width member will be accessible
by any member function of its derived class SmallBox.

• See and Run Program_5.cpp and the result is :


Classes and
MECHATRONICS STUDY PROGRAM Objects
C++ Class Constructor and Destructor (1)
The Class Constructor:

• A class constructor is a special member function of a class that is executed


whenever we create new objects of that class.
• A constructor will have exact same name as the class and it does not have any
return type at all, not even void. Constructors can be very useful for setting
initial values for certain member variables.

• Following example explains the concept of constructor: See and Run


Program_6.cpp and the result is :
Classes and
MECHATRONICS STUDY PROGRAM Objects
C++ Class Constructor and Destructor (2)
Parameterized Constructor::
• A default constructor does not have any parameter, but if you need, a constructor
can have parameters. This helps you to assign initial value to an object at the time
of its creation as shown in the following example:
• Following example explains the concept of constructor: See and Run
Program_7.cpp and the result is :

Using Initialization Lists to Initialize Fields:


• In case of parameterized constructor, you can use following syntax to initialize
the fields:

• If for a class C, you have multiple fields X, Y, Z, etc., to be initialized, then use
can use same syntax and separate the fields by comma as follows:
Homework
MECHATRONICS STUDY PROGRAM

C. Develop Constructor of the Class below, and provide initial values:


1. Cube
2. Cylinder
3. Ball
4. Cone
5. Ellips
6. Octahedron
7. Limas
8. Quadratic Equation
9. Temperature
10.Matrix with n=2
11.Matrix with n=3
12.Matrix with n=4
13.Matrix with n=5
Classes and
MECHATRONICS STUDY PROGRAM Objects
C++ Class Constructor and Destructor (2)
The Class Destructor:
• A destructor is a special member function of a class that is executed
whenever an object of it's class goes out of scope or whenever the delete
expression is applied to a pointer to the object of that class.
• A destructor will have exact same name as the class prefixed with a tilde (~)
and it can neither return a value nor can it take any parameters. Destructor
can be very useful for releasing resources before coming out of the
program like closing files, releasing memories etc.
• Following example explains the concept of destructor:
• See and Run Program_8.cpp

• When the above code is compiled and executed, it produces the


following result:
Classes and
MECHATRONICS STUDY PROGRAM Objects
C++ Copy Constructor (1)
 The copy constructor is a constructor which creates an object by
initializing it with an object of the same class, which has been created
previously. The copy constructor is used to:
 Initialize one object from another of the same type.
 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.
 If a copy constructor is not defined in a class, the compiler itself defines
one. If the class has pointer variables and has some dynamic memory
allocations, then it is a must to have a copy constructor. The most
common form of copy constructor is shown here:
classname (const classname &obj) {
// body of constructor
}
 Here, obj is a reference to an object that is being used to initialize
another object. Please see the source file Program_9.cpp.
Classes and
MECHATRONICS STUDY PROGRAM Objects
C++ Copy Constructor (2)
 When the Program_9.cpp code is compiled and executed, it produces the
following result:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
 Let us see the same example but with a small change to create another object using
existing object of the same type. Please see Program_10.cpp. When the
Program_10.cpp code is compiled and executed, it produces the following result:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!
Classes and
MECHATRONICS STUDY PROGRAM Objects
C++ Friend Functions (1)
 A friend function of a class is defined outside that class' scope but it has
the right to access all private and protected members of the class. Even
though the prototypes for friend functions appear in the class definition,
friends are not member functions.
 A friend can be a function, function template, or member function, or a
class or class template, in which case the entire class and all of its
members are friends.
 To declare a function as a friend of a class, precede the function
prototype in the class definition with keyword friend as follows:
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};.
Classes and
MECHATRONICS STUDY PROGRAM Objects
C++ Friend Functions (2)
 To declare all member functions of class ClassTwo as friends of class
ClassOne, place a following declaration in the definition of class
ClassOne:
friend class ClassTwo;.
 Please see Program_11.cpp. When the Program_11.cpp code is
compiled and executed, it produces the following result:
Width of box : 10
Homework
MECHATRONICS STUDY PROGRAM

D. Develop Friend Function of the Class below, and provide initial


values:
1. Cube, friend function: Area
2. Cylinder , friend function: Area
3. Ball , friend function: Area
4. Cone , friend function: Area
5. Ellips , friend function: Circumference
6. Octahedron , friend function: Circumference
7. Limas , friend function: Area
8. Quadratic Equation, friend function: Discriminant D
9. Temperature, friend function: Reamur
10.Matrix with n=2, friend function: Determinant
11.Matrix with n=3, friend function: Determinant
12.Matrix with n=4, friend function: Determinant
13.Matrix with n=5, friend function: Determinant
Classes and
MECHATRONICS STUDY PROGRAM Objects
The different between Structures and Class ? (1)

• Defining a Structure:
– To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member, for
your program. The format of the struct statement is this:
MECHATRONICS STUDY PROGRAM

The different between Structures and Class ? (2)

• The structure tag is optional and each member definition is


a normal variable definition, such as int i; or float f; or any
other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one
or more structure variables but it is optional. Here is the
way you would declare the Book structure:
Classes and
MECHATRONICS STUDY PROGRAM Objects
C++ Inline Functions (1)
 C++ inline function is powerful concept that is commonly used with classes.
If a function is inline, the compiler places a copy of the code of that function
at each point where the function is called at compile time.
 Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once
again otherwise it will continue with old functionality.
 To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler
can ignore the inline qualifier in case defined function is more than a line.
 A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
 Please see Program_13.cpp. When the Program_13.cpp code is
compiled and executed, it produces the following result:
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
Classes and
MECHATRONICS STUDY PROGRAM Objects
C++ this Pointer (1)
 Every object in C++ has access to its own address through an important
pointer called this pointer. The this pointer is an implicit parameter to all
member functions. Therefore, inside a member function, this may be used
to refer to the invoking object.
 Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer.
 Please see Program_14.cpp. When the Program_14.cpp code is
compiled and executed, it produces the following result:

Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
Classes and
MECHATRONICS STUDY PROGRAM Objects
Pointer to C++ classes (1)
 A pointer to a C++ class is done exactly the same way as a pointer to a
structure and to access members of a pointer to a class you use the
member access operator -> operator, just as you do with pointers to
structures. Also as with all pointers, you must initialize the pointer before
using it.
 Please see Program_15.cpp. When the Program_15.cpp code is
compiled and executed, it produces the following result:

Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102
Homework
MECHATRONICS STUDY PROGRAM

e. Use This Pointer of the Class below, to calculate its properties:


1. Cube
2. Cylinder
3. Ball
4. Cone
5. Ellips
6. Octahedron
7. Limas
8. Quadratic Equation
9. Temperature
10.Matrix with n=2
11.Matrix with n=3
12.Matrix with n=4
13.Matrix with n=5
MECHATRONICS STUDY PROGRAM

OUTLINE

C++ Classes and Objects:


 Class Definitions, Define C++ Objects, Accessing the Data Members &
 Classes & Objects in Detail
Inheritance
Overloading (Operator and Function)
Polymorphism in C++
 Abstraction
Encapsulation
Interfaces
C++ Inheritance
MECHATRONICS STUDY PROGRAM

C++ Inheritance
 One of the most important concepts in object-oriented programming is that
of inheritance. Inheritance allows us to define a class in terms of another
class, which makes it easier to create and maintain an application. This
also provides an opportunity to reuse the code functionality and fast
implementation time.

 When creating a class, instead of writing completely new data members


and member functions, the programmer can designate that the new class
should inherit the members of an existing class. This existing class is called
the base class, and the new class is referred to as the derived class.

 The idea of inheritance implements the is a relationship. For example,


mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well
and so on.
C++ Inheritance
MECHATRONICS STUDY PROGRAM

Base & Derived Classes


 A class can be derived from more than one classes, which means it can
inherit data and functions from multiple base classes. To define a derived
class, we use a class derivation list to specify the base class(es). A class
derivation list names one or more base classes and has the form:
class derived-class: access-specifier base-class
 Where access-specifier is one of public, protected, or private, and base-
class is the name of a previously defined class. If the access-specifier is
not used, then it is private by default.

 Consider a base class Shape and its derived class Rectangle as follows in
Please see Program_17.cpp. When the Program_17.cpp code is
compiled and executed, it produces the following result:

Total area: 35
C++ Inheritance
MECHATRONICS STUDY PROGRAM

Access Control and Inheritance (1)


 A derived class can access all the non-private members of its base class.
Thus base-class members that should not be accessible to the member
functions of derived classes should be declared private in the base class.
 We can summarize the different access types according to who can access
them in the following way:

 A derived class inherits all base class methods with the following
exceptions:
 Constructors, destructors and copy constructors of the base class.
 Overloaded operators of the base class.
 The friend functions of the base class.
C++ Inheritance
MECHATRONICS STUDY PROGRAM

Type of Inheritance (1)


 When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is
specified by the access-specifier as explained above.
 We hardly use protected or private inheritance, but public inheritance is
commonly used. While using different type of inheritance, following rules are
applied:
 Public Inheritance: When deriving a class from a public base class, public
members of the base class become public members of the derived class and
protected members of the base class become protected members of the derived
class. A base class's private members are never accessible directly from a
derived class, but can be accessed through calls to the public and protected
members of the base class.
 Protected Inheritance: When deriving from a protected base class, public and
protected members of the base class become protected members of the derived
class.
 Private Inheritance: When deriving from a private base class, public and
protected members of the base class become private members of the derived
class.
C++ Inheritance
MECHATRONICS STUDY PROGRAM

Multiple Inheritances (1)


 A C++ class can inherit members from more than one class and here is the
extended syntax:
class derived-class: access baseA, access baseB....

 Where access is one of public, protected, or private and would be given for
every base class and they will be separated by comma as shown above. Let
us try see Program_18.cpp. When the Program_18.cpp code is compiled
and executed, it produces the following result:

Total area: 35
Total paint cost: $2450
MECHATRONICS STUDY PROGRAM

OUTLINE

C++ Classes and Objects:


 Class Definitions, Define C++ Objects, Accessing the Data Members &
 Classes & Objects in Detail
Inheritance
Overloading (Operator and Function)
Polymorphism in C++
 Abstraction
Encapsulation
Interfaces
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

 C++ allows you to specify more than one definition for a function
name or an operator in the same scope, which is called function
overloading and operator overloading respectively.

 An overloaded declaration is a declaration that had been declared


with the same name as a previously declared declaration in the
same scope, except that both declarations have different
arguments and obviously different definition (implementation).

 When you call an overloaded function or operator, the compiler


determines the most appropriate definition to use by comparing
the argument types you used to call the function or operator with
the parameter types specified in the definitions. The process of
selecting the most appropriate overloaded function or operator is
called overload resolution.
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Function overloading in C++


 You can have multiple definitions for the same function name in the
same scope. The definition of the function must differ from each other by
the types and/or the number of arguments in the argument list. You can
not overload function declarations that differ only by return type.
 Following is the example where same function print() is being used to
print different data types. Please see Program_19.cpp When the
Program_19.cpp code is compiled and executed, it produces the
following result:

Printing int: 5
Printing float: 500.263
Printing character: Hello C++
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Operators overloading in C++ (1)


 You can redefine or overload most of the built-in operators available in
C++. Thus a programmer can use operators with user-defined types as
well.
 Overloaded operators are functions with special names the keyword
operator followed by the symbol for the operator being defined. Like any
other function, an overloaded operator has a return type and a
parameter list.
Box operator+(const Box&);
 It declares the addition operator that can be used to add two Box objects
and returns final Box object. Most overloaded operators may be defined
as ordinary non-member functions or as class member functions. In case
we define above function as non-member function of a class then we
would have to pass two arguments for each operand as follows:
Box operator+(const Box&, const Box&);
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Operators overloading in C++ (2)

 Following is the example to show the concept of operator over loading


using a member function. Here an object is passed as an argument
whose properties will be accessed using this object, the object which will
call this operator can be accessed using this operator as explained in
Program_20.cpp below.

 When the above code is compiled and executed, it produces the


following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Operators overloading in C++ (3)


Overloadable/Non-overloadableOperators:
 Following is the list of operators which can be overloaded:

 Following is the list of operators, which can not be overloaded:


C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Operators overloading in C++ (3)


Operator Overloading Examples:
 Here are various operator overloading examples to help you in
understanding the concept.
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Unary operators overloading in C++ (1)


 The unary operators operate on a single operand and following are the
examples of Unary operators:
 The increment (++) and decrement (--) operators.
 The unary minus (-) operator.
 The logical not (!) operator.
 The unary operators operate on the object for which they were called
and normally, this operator appears on the left side of the object, as in
!obj, -obj, and ++obj but sometime they can be used as postfix as well
like obj++ or obj--.
 Following example in Program_21.cpp below explain how minus (-)
operator can be overloaded for prefix as well as postfix usage. When the
above code is compiled and executed, it produces the following result:
F: -11 I:-10
F: 5 I:-11
Hope above example makes your concept clear and you can apply
similar concept to overload Logical Not Operators (!).
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Overloading Increment ++ and Decrement --(1)

 The increment (++) and decrement (--) operators are two important
unary operators available in C++.

 Following example explain how increment (++) operator can be


overloaded for prefix as well as postfix usage. Similar way, you can
overload operator (--). Please see the example in Program_22.cpp.
When the above code is compiled and executed, it produces the
following result:
H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Binary operators overloading in C++ (1)

 The unary operators take two arguments and following are the examples
of Binary operators. You use binary operators very frequently like
addition (+) operator, subtraction (-) operator and division (/) operator.

 Following example explains how addition (+) operator can be


overloaded. Similar way, you can overload subtraction (-) and division (/)
operators. Please see the example in Program_23.cpp. When the
above code is compiled and executed, it produces the following result:

Volume of Box1 : 210


Volume of Box2 : 1560
Volume of Box3 : 5400
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Relational operators overloading in C++ (1)

 There are various relational operators supported by C++ language like


(<, >, <=, >=, ==, etc.) which can be used to compare C++ built-in data
types.
 You can overload any of these operators, which can be used to compare
the objects of a class.
 Following example explains how a < operator can be overloaded and
similar way you can overload other relational operators. Please see the
example in Program_24.cpp. When the above code is compiled and
executed, it produces the following result:

D2 is less than D1
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Input/Output operators overloading in C++ (1)

 C++ is able to input and output the built-in data types using the stream
extraction operator >> and the stream insertion operator <<. The stream
insertion and stream extraction operators also can be overloaded to
perform input and output for user-defined types like an object.
 Here, it is important to make operator overloading function a friend of the
class because it would be called without creating an object.
 Following example explains how extraction operator >> and insertion
operator <<. Please see the example in Program_25.cpp. When the
above code is compiled and executed, it produces the following result:
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Assignment operators overloading in C++ (1)

 You can overload the assignment operator (=) just as you can other
operators and it can be used to create an object just like the copy
constructor.

 Following example explains how an assignment operator can be


overloaded. Please see the example in Program_26.cpp. When the
above code is compiled and executed, it produces the following result:

First Distance : F: 11 I:10


Second Distance :F: 5 I:11
First Distance :F: 5 I:11
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Function call operator () overloading in C++ (1)

 The function call operator () can be overloaded for objects of class type.
When you overload ( ), you are not creating a new way to call a function.
Rather, you are creating an operator function that can be passed an
arbitrary number of parameters.

 Following example explains how a function call operator () can be


overloaded. Please see the example in Program_27.cpp. When the
above code is compiled and executed, it produces the following result:

First Distance : F: 11 I:10


Second Distance :F: 30 I:120
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Subscripting [] operator overloading in C++ (1)

 The subscript operator [] is normally used to access array elements. This


operator can be overloaded to enhance the existing functionality of C++
arrays.

 Following example explains how a subscript operator [] can be


overloaded. Please see the example in Program_28.cpp. When the
above code is compiled and executed, it produces the following result:

Value of A[2] : 2
Value of A[5] : 5
Index out of bounds
Value of A[12] : 0
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Class member access operator (->) overloading in C++ (1)


 The class member access operator (->) can be overloaded but it is bit
trickier. It is defined to give a class type a "pointer-like" behavior. The
operator -> must be a member function. If used, its return type must be a
pointer or an object of a class to which you can apply.
 The operator-> is used often in conjunction with the pointer-dereference
operator * to implement "smart pointers." These pointers are objects that
behave like normal pointers except they perform other tasks when you
access an object through them, such as automatic object deletion either
when the pointer is destroyed, or the pointer is used to point to another
object.
 The dereferencing operator-> can be defined as a unary postfix operator.
That is, given a class:
class Ptr{
//...
X * operator->();
};
C++ Overloading
MECHATRONICS STUDY PROGRAM (Operator and Function)

Class member access operator (->) overloading in C++ (2)


 Objects of class Ptr can be used to access members of class X in a very
similar manner to the way pointers are used. For example:
void f(Ptr p )
{
p->m = 10 ; // (p.operator->())->m = 10
}
 The statement p->m is interpreted as (p.operator->())->m. Using the same
concept, following example explains how a class access operator -> can be
overloaded. Please see the example in Program_29.cpp. When the above
code is compiled and executed, it produces the following result:

10
12
11
...
21
MECHATRONICS STUDY PROGRAM

OUTLINE

C++ Classes and Objects:


 Class Definitions, Define C++ Objects, Accessing the Data Members &
 Classes & Objects in Detail
Inheritance
Overloading (Operator and Function)
Polymorphism in C++
 Abstraction
Encapsulation
Interfaces
Polymorphism in C++
MECHATRONICS STUDY PROGRAM

Polymorphism in C++ (1)

 The word polymorphism means having many forms. Typically,


polymorphism occurs when there is a hierarchy of classes and they are
related by inheritance.
 C++ polymorphism means that a call to a member function will cause a
different function to be executed depending on the type of object that
invokes the function.
 Consider the following example where a base class has been derived by
other two classes. Please see the example in Program_30.cpp. When
the above code is compiled and executed, it produces the following
result:

Parent class area


Parent class area
Polymorphism in C++
MECHATRONICS STUDY PROGRAM

Polymorphism in C++ (2)


 The reason for the incorrect output is that the call of the function area() is
being set once by the compiler as the version defined in the base class.
This is called static resolution of the function call, or static linkage - the
function call is fixed before the program is executed. This is also
sometimes called early binding because the area() function is set during
the compilation of the program.
 But now, let's make a slight modification in our program and precede the
declaration of area() in the Shape class with the keyword virtual so that it
looks like this:
Please see the example in Program_31.cpp. After this
slight modification, when the previous example code is
compiled and executed, it produces the following result:

Rectangle class area


Triangle class area
Polymorphism in C++
MECHATRONICS STUDY PROGRAM

Polymorphism in C++ (3)


 This time, the compiler looks at the contents of the pointer instead of it's
type. Hence, since addresses of objects of tri and rec classes are stored
in *shape the respective area() function is called.
 As you can see, each of the child classes has a separate implementation
for the function area(). This is how polymorphism is generally used. You
have different classes with a function of the same name, and even the
same parameters, but with different implementations.
 Virtual Function:
 A virtual function is a function in a base class that is declared using
the keyword virtual. Defining in a base class a virtual function, with
another version in a derived class, signals to the compiler that we
don't want static linkage for this function.
 What we do want is the selection of the function to be called at any
given point in the program to be based on the kind of object for which
it is called. This sort of operation is referred to as dynamic linkage, or
late binding.
Polymorphism in C++
MECHATRONICS STUDY PROGRAM

Polymorphism in C++ (4)


 Pure Virtual Functions:
 It's possible that you'd want to include a virtual function in a base
class so that it may be redefined in a derived class to suit the objects
of that class, but that there is no meaningful definition you could give
for the function in the base class.
 We can change the virtual function area() in the base class to the
following:

The = 0 tells the compiler that the function


has no body and above virtual function will
be called pure virtual function.
MECHATRONICS STUDY PROGRAM

OUTLINE

C++ Classes and Objects:


 Class Definitions, Define C++ Objects, Accessing the Data Members &
 Classes & Objects in Detail
Inheritance
Overloading (Operator and Function)
Polymorphism in C++
 Abstraction
Encapsulation
Interfaces
MECHATRONICS STUDY PROGRAM Data Abstraction in C++

Data Abstraction in C++ (1)


 Data abstraction refers to, providing only essential information to the
outside world and hiding their background details, i.e., to represent the
needed information in program without presenting the details.
 Data abstraction is a programming (and design) technique that relies on
the separation of interface and implementation.
 Let's take one real life example of a TV, which you can turn on and off,
change the channel, adjust the volume, and add external components
such as speakers, VCRs, and DVD players, BUT you do not know its
internal details, that is, you do not know how it receives signals over the
air or through a cable, how it translates them, and finally displays them
on the screen.
 Thus, we can say a television clearly separates its internal
implementation from its external interface and you can play with its
interfaces like the power button, channel changer, and volume control
without having zero knowledge of its internals.
MECHATRONICS STUDY PROGRAM Data Abstraction in C++

Data Abstraction in C++ (2)


 Now, if we talk in terms of C++ Programming, C++ classes provides great level
of data abstraction. They provide sufficient public methods to the outside world to
play with the functionality of the object and to manipulate object data, i.e., state
without actually knowing how class has been implemented internally.
 For example, your program can make a call to the sort() function without knowing
what algorithm the function actually uses to sort the given values. In fact, the
underlying implementation of the sorting functionality could change between
releases of the library, and as long as the interface stays the same, your function
call will still work.
 In C++, we use classes to define our own abstract data types (ADT). You can
use the cout object of class ostream to stream data to standard output like this:

Here, you don't need to understand how cout


displays the text on the user's screen. You need
to only know the public interface and the
underlying implementation of cout is free to
change.
MECHATRONICS STUDY PROGRAM Data Abstraction in C++

Access Labels Enforce Abstraction (1)


 In C++, we use access labels to define the abstract interface to the
class. A class may contain zero or more access labels:
 Members defined with a public label are accessible to all parts of the
program. The data-abstraction view of a type is defined by its public
members.
 Members defined with a private label are not accessible to code that
uses the class. The private sections hide the implementation from
code that uses the type.
 There are no restrictions on how often an access label may appear.
Each access label specifies the access level of the succeeding member
definitions. The specified access level remains in effect until the next
access label is encountered or the closing right brace of the class body
is seen.
MECHATRONICS STUDY PROGRAM Data Abstraction in C++

Benefits of Data Abstraction (1)


 Data abstraction provides two important advantages:
 Class internals are protected from inadvertent user-level errors,
which might corrupt the state of the object.
 The class implementation may evolve over time in response to
changing requirements or bug reports without requiring change in
user-level code.
 By defining data members only in the private section of the class, the
class author is free to make changes in the data. If the implementation
changes, only the class code needs to be examined to see what affect
the change may have. If data are public, then any function that directly
accesses the data members of the old representation might be broken.
MECHATRONICS STUDY PROGRAM Data Abstraction in C++

Data Abstraction Example (1)


 Any C++ program where you implement a class with public and private
members is an example of data abstraction. Consider the following
example. Please see the example in Program_32.cpp. When the above
code is compiled and executed, it produces the following result:
Total 60
 Above class adds numbers together, and returns the sum. The public
members addNum and getTotal are the interfaces to the outside world
and a user needs to know them to use the class. The private member
total is something that the user doesn't need to know about, but is
needed for the class to operate properly.
 Designing Strategy:
 Abstraction separates code into interface and implementation. So while designing your
component, you must keep interface independent of the implementation so that if you
change underlying implementation then interface would remain intact.
 In this case whatever programs are using these interfaces, they would not be impacted
and would just need a recompilation with the latest implementation.
MECHATRONICS STUDY PROGRAM

OUTLINE

C++ Classes and Objects:


 Class Definitions, Define C++ Objects, Accessing the Data Members &
 Classes & Objects in Detail
Inheritance
Overloading (Operator and Function)
Polymorphism in C++
 Abstraction
Encapsulation
Interfaces
MECHATRONICS STUDY PROGRAM Data Abstraction in C++

Data Encapsulation in C++ (1)


 Any C++ program where you implement a class with public and private
members is an example of data abstraction. Consider the following
example. Please see the example in Program_32.cpp. When the above
code is compiled and executed, it produces the following result:
Total 60
 Above class adds numbers together, and returns the sum. The public
members addNum and getTotal are the interfaces to the outside world
and a user needs to know them to use the class. The private member
total is something that the user doesn't need to know about, but is
needed for the class to operate properly.
 Designing Strategy:
 Abstraction separates code into interface and implementation. So while designing your
component, you must keep interface independent of the implementation so that if you
change underlying implementation then interface would remain intact.
 In this case whatever programs are using these interfaces, they would not be impacted
and would just need a recompilation with the latest implementation.
MECHATRONICS STUDY PROGRAM

OUTLINE

C++ Classes and Objects:


 Class Definitions, Define C++ Objects, Accessing the Data Members &
 Classes & Objects in Detail
Inheritance
Overloading (Operator and Function)
Polymorphism in C++
 Abstraction
Encapsulation
Interfaces
MECHATRONICS STUDY PROGRAM Data Abstraction in C++

Interfaces in C++ (Abstract Classes) (1)


 An interface describes the behavior or capabilities of a C++ class without
committing to a particular implementation of that class.
 The C++ interfaces are implemented using abstract classes and these
abstract classes should not be confused with data abstraction which is a
concept of keeping implementation details separate from associated
data.
 A class is made abstract by declaring at least one of its functions as pure
virtual function. A pure virtual function is specified by placing "= 0" in its
declaration as
MECHATRONICS STUDY PROGRAM Data Abstraction in C++

Interfaces in C++ (Abstract Classes) (2)


 The purpose of an abstract class (often referred to as an ABC) is to
provide an appropriate base class from which other classes can inherit.
Abstract classes cannot be used to instantiate objects and serves only
as an interface. Attempting to instantiate an object of an abstract class
causes a compilation error.
 Thus, if a subclass of an ABC needs to be instantiated, it has to
implement each of the virtual functions, which means that it supports the
interface declared by the ABC. Failure to override a pure virtual function
in a derived class, then attempting to instantiate objects of that class, is a
compilation error.
 Classes that can be used to instantiate objects are called concrete
classes.
 Abstract Class Example:Consider the following example where parent
class provides an interface to the base class to implement a function
called getArea(): Please see the example in Program_33.cpp.
MECHATRONICS STUDY PROGRAM Data Abstraction in C++

Interfaces in C++ (Abstract Classes) (2)


 When the above code is compiled and executed, it produces the
following result:

 You can see how an abstract class defined an interface in terms of


getArea() and two other classes implemented same function but with
different algorithm to calculate the area specific to the shape.
 Designing Strategy:
 An object-oriented system might use an abstract base class to provide a common and
standardized interface appropriate for all the external applications. Then, through
inheritance from that abstract base class, derived classes are formed that all operate
similarly.
 The capabilities (i.e., the public functions) offered by the external applications are
provided as pure virtual functions in the abstract base class. The implementations of
these pure virtual functions are provided in the derived classes that correspond to the
specific types of the application.
 This architecture also allows new applications to be added to a system easily, even
after the system has been defined.
MECHATRONICS STUDY PROGRAM

Dr. Ir. Hanny J. Berchmans, M.T. M.Sc.


+628775006229
[email protected]

You might also like