Unit-1 Oop Basics
Unit-1 Oop Basics
Object Oriented
Programming
Saifee Vohra
Published by :
Object Oriented Programming, 2017 Edition
By Saifee Vohra
Copyright © 2017 Saifee Vohra
No part of this book may be reproduced in any form or by any electronic or mechanical
means including information storage and retrieval systems, without permission in writing
from the author. The only exception is by a reviewer, who may quote short excerpts in a
review. For permission requests, write to the author at [email protected]
Published by
Cover design by
Printed in India.
ISBN-13:
ISBN-10:
This book is dedicated to the ones who dream, who have that spark of
intelligence and greatness.
Preface
Welcome and thank you for choosing this book. This book has been mainly designed for
the specific requirements of D.E. fourth semester syllabus of the Gujarat Technological
University, but it can also used for other curriculams where C++ is offered. This book can
be used as a complete textbook or a reference book.
Real life examples have been used throughout the book, to illustrate concepts and how
to apply them. Also, related explanations in programs will help students to understand
why things work as they do. Simple Examples, help a beginner to understand difficult
OOP concepts. We’ve found from our experience that beginners are generally happy
when they can understand the whole concept.
This book presents the material in a careful sequence, so the reader can easily
understand each concept before moving on. We have tried our best to answer the
important question of ‘‘why?’’ for majority topics not just the “what?”. We believe that
by understanding how things work as they do, students will understand basic
fundamentals of the subject clearly and it will also make learning more interesting.
GTU FAQ section at the end of the each chapter contains GTU Exam questions from all
branches where C++ subject is offered such as MCA, Electronics and Communications
engineering and just not only from the CE and IT discipline.
Please note that if you don’t have the latest version of the compiler then your compiler
may not support many features discussed in this book. All codes snippets and programs
of this book are tested with code blocks IDE.
No matter how much a writer takes care about the errors, some always remains. If you
find anything you believe to be an error, please reach us at [email protected]. We
will happily acknowledge your help both online and in later editions.
As a reader you are most important critic of this book, We would be glad to receive
suggestions on improvements of this book. Any contributions to the book which can be
helpful to other readers such as materials, programming excercises, study tips are also
welcome.
Acknowledgements
No one who achieves success does so without acknowledging the help of others. The
wise and confident acknowledge this help with gratitude. --Alfred North Whitehead
We like to thank all the people who have supported us while writing this book and who
have made this book the best it can be.
A big thank you to the reviewers who provided helpful and valuable comments during
the development of this book, including Prof. Parvez Faruki, Prof. Nandu Fatak.
We would like to thank all our teachers and all our students who are our teachers as well.
We are thankful to our parents for their blessings.
Thanks to the people at GTP Publications for providing us this great opportunity to
become authors of this book. We appreciate that they believed in us, to provide the
direction and knowledge to make this book a reality.
We learned a lot and had a great fun while writing this book. We hope you will have the
same experience while reading it.
And now finally wishes to you,
Dear Reader, Happy Learning and have a great fun with C++!
-- Saifee Vohra
0 TABLE OF CONTENTS
0 Table of Contents ...................................................................................................... vi
1 Concepts of OOP ........................................................................................................ 1
1.1 Introduction ......................................................................................................... 1
1.2 Procedure Oriented Programming (POP) ............................................................ 1
1.3 Object Oriented Programming ............................................................................ 4
1.4 Concepts of OOP .................................................................................................. 5
1.4.1 Objects.......................................................................................................... 5
1.4.2 Class .............................................................................................................. 5
1.4.3 Encapsulation: Hiding your internal workings ............................................. 6
1.4.4 Abstraction: Focusing on what is important ................................................ 7
1.4.5 Inheritance ................................................................................................... 8
1.4.6 Polymorphism .............................................................................................. 9
1.4.7 Message Passing ........................................................................................... 9
1.5 Benefits of Object Oriented Programming ........................................................ 10
1.6 Applications of OOP ........................................................................................... 10
2 C++ Basics ................................................................................................................. 12
2.1 C++ Introduction ................................................................................................ 12
2.2 Famous Real Life Applications of C++ ................................................................ 12
2.3 First C++ Program .............................................................................................. 12
2.4 Comments.......................................................................................................... 14
2.5 Tokens ................................................................................................................ 15
2.5.1 Keywords .................................................................................................... 15
2.5.2 Identifiers ................................................................................................... 15
2.6 Data Types ......................................................................................................... 16
2.6.1 Primary Data Type ...................................................................................... 17
2.6.2 Derived Data Types .................................................................................... 20
2.6.3 User-Defined Types .................................................................................... 21
Table of Contents | vii
Course Syllabus:
Concepts of OOP |1
1 CONCEPTS OF OOP
"In programming, the hard part isn't solving problems, but deciding what
problems to solve." -- Paul Graham
1.1 Introduction
Software design and development is all about managing complexity. Nowadays users
want more and more features. The changing customer and corporate needs require
software which are quickly adaptable to changes. Tools and technologies are changing
faster than ever.
It is necessary to manage the complexity and changing needs. The successful software
development is managing such complexity. Object Oriented Programming helps in
managing such complexity with its useful features.
Object Oriented Programming (OOP) development means looking at a software system
in terms of the objects. An object is any real world entity which is distinguishable from
each other.
Software development in an object oriented way makes it easier to develop the
application into separate objects, to focus on the most important aspects of each object,
and to look at the relationships between those objects.
Programming is a process to instruct a computer on how to perform a particular task
using the program. A program is a set of instructions that tells a computer what to do in
order to solve a particular problem. The different approaches of the programming
process is known as programming paradigms.
Two of the most important approaches are procedural programming and object-oriented
programming.
When programming any system, we are essentially dealing with data and the functions
that changes that data. These two fundamental aspects of programming are handled
differently in Procedural Oriented Programming and Object Oriented Programming.
Procedural programming emphasizes on functions i.e. doing things step by step. Most of
the early programming languages are all procedural. Examples of procedural languages
include FORTRAN, Pascal and C.
In POP, functions have no fundamental relationship with the data they operate on. In
large applications most of the data are shared by different functions. Any function can
access and modify such shared or global data. This makes development in POP very
complex. As we are focusing on functions rather than main element data.
Suppose in a new project whenever you need to store something, you create a variable.
To work with different functions in your program, you make your variables global. Now
as need arises to add more features, you write more functions. There is a possibility that
certain global data you stored before, are needed to modify so that they can work with
the newly added functions.
Concepts of OOP |3
As your project gets bigger, it becomes very complex to add new features. Because you
need to remember what all your global variables are storing and which functions are
modifying them. It may possible that any new function may accidentally change values
of these global variables.
Now imagine a project 1000 times bigger than yours and multiple people working on it.
How can everyone on the team remember what all those functions are doing on global
data? What if someone has left the job and newly hired programmer make changes which
can crash your project because he has no idea about dependency of functions and global
data.
Another serious limitation with the procedural approach is that it does not model real
world problems very well. Imagine making a soccer game in C, how will you model
players, their behaviors? It is very difficult.
❖ Characteristics of Procedural Programming:
Programs are divided into functions.
Functions get more importance than the data in a program.
Most of the functions share global data.
Since global data are shared from function to function, the global data may be
changed by the function.
The program design of procedure oriented programming follows the top
down methodology.
The use of global data increases the possibility of errors and thus leads to the
code maintenance problem.
Difficult to maintain data integrity
There is no perfect way for data hiding.
Not enough support for data abstraction.
The modification of global data also requires the modification of those
functions using it.
Difficulty in adding more features to existing program.
Object Orientated Programming does not ignore the data or the procedure. It combines
the both Procedure Oriented Programming view, where the focus is on the functions and
an OOP view where the focus is on the data. It adds concepts such as Inheritance
(reusability), information hiding , Polymorphism for easy software development and
managing software complexity.
❖ Characteristics of Object Oriented Programming are:
Emphasis is on the data.
Programs are divided into the objects.
Data and Functions that operate on the data are grouped together into objects.
Data is hidden and can be accessed only by the functions associated with that
Object.
Objects may communicate with each other through functions.
New data and functions can be added easily.
Uses bottom-up approach in program design.
In bottom-up design, the problem solving start from the bottom. It means start with the
problems that you already know how to solve and for which you might have a reusable
software component. From there, you can work upwards and solve the overall problem.
For example, consider the car manufacturing process. If a car supposed to be designed
as a single machine, then it is very difficult task. But, when divided into many parts, such
as wheels, engine, doors, etc. then Individual designing of the parts become simpler. Each
part is created and tested separately and then assembled into the final product. In same
manner bottom-up software development approach in OOP works.
Think about classes and objects as a process of making a cake. A class is like a recipe for
making the cake. The recipe is not the cake, you can't eat the recipe. If you prepare the
cake from the recipe then you can eat it. The edible cake is an object or an instance of
the cake class and the recipe is the class.
You can make as many cakes as you want by using the same cake recipe with different
sizes. Similarly, you can create many objects of the same class with different properties.
How does the house built? Architect first draws a blueprint of the house. After the
blueprint is finished, the house can be built based on the blueprint. In this case the
blueprint for the house is the class, and the physical house is the object.
The first reason is to provide a simple way to use your application without the need to
understand the complexity inside. For example, while playing a game you don’t need to
know the internal logic and coding of the game. It is sufficient for a person to know how
to play game with different commands and how to clear different levels. Hiding the
internal complexity of the game from the user allows anyone to play a game, not just the
developers who have created the game. In the same way, hiding the complex
functionality of your application from the user allows anyone to use it. This concept of
hiding information i.e. encapsulation is the key to object-oriented programming.
The second reason for hiding internal workings is to manage the changes. Even though
the internal coding of the game changes, such as improvement in memory usage,
addition of new levels etc. the game itself functions the same way as before. Users don’t
require to know about changes made to the game and they can easily use the system as
before.
1.4.4 Abstraction: Focusing on what is important
Suppose you want to create a program which allows the management of the students for
some institute. Now which information of the students will be needed for the
development of the program as students can be characterized with many properties such
as:
name
height
date of birth
address
hair color
hobbies
marks
eye color
favorite food
Not all of these properties are necessary to develop the given program. Are eye color and
favorite food are really that relevant to the institute? No. Only essential details are
required to solve a particular problem. Abstraction helps in selecting relevant details.
Abstraction represent the essential details while ignoring nonessential details.
Two people have different abstract models of the same thing. For example, when you are
using any website clicking on some menu or button internally fires some event and gives
you desired result. But as a user you only require to know how to get result by clicking
that button, internally which code fires that event is not necessary for you. This is your
abstract view of that application.
Now if you are a programmer of that website, you must know which code should fired
after clicking that button. At your level, it is essential to know how the code works. So
when you move down the abstraction layer, you will get more details.
|8 Object Oriented Programming
You may confuse by both abstraction and encapsulation because both hide something.
Both are much related but very different concepts. Abstraction focuses on the external
behavior of an object, while encapsulation focuses upon the implementation i.e. internal
workings of the object.
1.4.5 Inheritance
In procedural programming, it is very common to copy the code and to add or to modify
the certain attributes to introduce new features. But problem with this approach is that
it generates duplicate code, which can create maintenance issues.
Different kinds of objects often have a certain amount of properties common with each
other, yet each one also defines additional features that make them different. For
example, calculator and scientific calculator. Instead of copying common features Object-
oriented Programming allows to inherit common features from other objects.
Inheritance is the process in which the properties of one class (base or parent class) are
shared by another class (derived or child class). The derived class may add some
properties which are unique to itself.
The main use of inheritance is reusability. Instead of writing or copying common code
inheritance allows you to reuse existing code. For example, while making program for
scientific calculator you can reuse some of the code from calculator program which has
been made already.
you in saving the development time by providing reusability because much of the code
needed for new class is already written as a base (old) class. It also helps you in reducing
the testing time because the existing code has been already tested so it is reliable.
1.4.6 Polymorphism
Polymorphism means one name having multiple forms.
Polymorphism means an application can interact with many different kinds of objects
and gets a different results depending upon which kind of object is using the application.
This simply means that, you have the same interface for something but can have different
behavior based on the object type. Think about a DVD player. When you put a regular
DVD in the player what happens? It works, right? How about when you put a CD in the
player? It also plays. The interface of the player is the same for both types, but the
behavior is different. Internally, there is a different implementation for the playing of a
disc based on the type.
Another example, a person can speak many languages. But which language he speaks is
based on context or situation. So here person is same but the speaking of language is
different based on the context.
There are two types of polymorphism:
Static or Compile time polymorphism
Dynamic or Runtime polymorphism
With compile time polymorphism, the same functions or operators can perform different
actions depending on the object that invokes it. For example, same add() function can
add two integers, floats etc. Same ‘+’ operator can also be used to add two numbers, two
characters.
Dynamic binding means that the code to be executed for a specific function call is not
known until run-time. Dynamic binding is also known as late binding or run-time binding.
It provides a mechanism to the program to determine how to act based on the
information which is provided to it only when it is running.
For Example, each bank has different rate for interest calculations. So which
InterestCalc() function will be called is decided by which class object has called that
function. If SBI object has called the function then the SBI InterestCalc() version of the
function is called. Here all functions have the same name but the implementation of each
is different and which function is called will be decided at runtime. In C++, virtual
functions are used to implement dynamic binding.
1.4.7 Message Passing
A single object by itself may not be very useful because an application contains many
objects. Message passing is the process where one object passes a message to another
| 10 Object Oriented Programming
object and the receiving object responds by executing one of its function. So a method
(function) is invoked on delivery of the corresponding message by the called object.
In OOP objects communicate with each other through message passing. When one object
wants another object to perform some action (i.e. call one of its methods), first object
sends a message to other object.
A message is composed of three elements:
The object to which the message is addressed.
The name of the method to perform.
Any parameters needed by the method.
1.5 Benefits of Object Oriented Programming
OOP provides functionalities to model real-world applications more effectively.
This allows modelling complex systems of real world into convenient software
solutions.
OOP provides information hiding by providing a way to communicate with object,
only with an object's methods. Thus, its internal implementation details remain
hidden from the outside world.
Code reuse enables faster software development. Object Oriented Programming
languages have rich set of reusable libraries of classes, and code developed during
previous projects is also reusable in future projects.
It provides easy debugging and pluggabilty. If a particular object has non
consistent behavior, you can simply remove it from your application and replace
it with different object without affecting other object’s code. This is similar to
solving problems in the real world. If some part becomes non-functional, you
replace only that part, not the entire machine.
It is easy to extend existing application as new classes can be created with small
differences to existing ones using inheritance.
OOP languages are effective in creating better GUI (graphical user interface)
applications.
A class can be written and maintained independently of the source code for other
class. Thus Different people can work on different parts of the project
simultaneously.
OOP Improves software maintainability because reusing already created and
tested code reduce time in maintenance.
1.6 Applications of OOP
Nowadays OOP has gain so much importance in software development. OOP applications
can simplify a complex problem and develop a software solution for that. You can see
many examples of OOP in day-to-day used applications and devices. For example, the
major mobile device platforms, iPhone, Android, Windows use the programming
language Objective-C, Java and .NET respectively which are all based on objects.
Concepts of OOP | 11
❖ GTU FAQ ❖
1. Differentiate procedural programming with object oriented programming.
2. What is Object oriented programming? Explain features of Object oriented
programming.
3. Explain basic concepts of Object-Oriented Programming with suitable example.
4. Compare object and classes.
5. Differentiate C and C++.
6. Compare structured programming with object oriented programming.
7. Explain: Abstraction and Encapsulation
8. List the characteristics of object oriented programming.
9. Describe any two characteristics of OOP.
10. List benefits of OOP.
11. Distinguish between Dynamic binding and message passing