0% found this document useful (0 votes)
36 views18 pages

Chapter 1

Uploaded by

athilahnurin03
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)
36 views18 pages

Chapter 1

Uploaded by

athilahnurin03
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/ 18

DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

LECTURE 1

INTRODUCTION TO C++
AND
OBJECT ORIENTED PROGRAMMING

Objectives

At the end of this lecture, students should be able to :

 Understand what is C++.


 Know the history of C++.
 Understand the concepts of object-oriented programming (OOP).
 Know the advantages of using OOP.
 Make comparison between C and C++.

MULTIMEDIA UNIVERSITY 1
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

1.0 What is C++?


 C++ is an object-oriented language.
 C is the predecessor of C.
 C++ is superset to C.
 C++ derives ideas from procedural programming and combines them with some of the
new concepts and elements in carrying out programming.

C++ Procedural Programming


C/C++

Object-oriented programming

The figure above shows that C++ is superset to C

1.1 History of C++


 The early 1980s, Bjarne Stroustrup has developed a high level language called C++ at
Bell Laboratories in Murray Hill, New Jersey.
 C++ was developed from C.
 Before, C++ was known as “C with class”. However, in 1983, the name was changed to
C++.
 C++ has a combination of new fundamental concepts that has been the basis for object-
oriented programming.

1.2 Procedural and Object Orientations


 High-level languages may be categorized by whether they are oriented toward
procedures or objects.
 Procedures are modules of code that transform data. They perform a set of actions with
or without data input. The results of the action(s) performed may or may not be returned
to other portions of the program or output device. Procedural languages may refer to their
basic work unit by various names. For example, procedures in C and C++ are known as a
function. Java procedures (and sometimes C++ procedures) are called methods.
 Objects are software constructs modelled after real world things. They were originally
conceived to provide visual support for graphical user interfaces (GUIs). A screen
window, for example, may be analogized to a real window. Accordingly, the window has a
color, position, and size (among other attributes) and methods to set or alter the same
attributes.

MULTIMEDIA UNIVERSITY 2
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

1.3 Example of first C++ program

This program will display the sentence “Hello!”.

//First C++ program (1) Comment


#include <iostream.h> (2) pre-processor directive
int main()
{ (3) function header
cout<<”Hello!”<<endl;
(5) display instruction
return 0; (6) Return value
}

(4) main() function body

1. Comment
 Comment is used to make a program easier be read.

2. Pre-processor directives
 A component in C++ compiler will direct the pre-processor directives to insert
the content of iostream.h file into the program

3. Function header
 Consists of value, which will be returned (in the example, the value is of type
int).
 It is a function, which will be first executed by the compiler.

4. Main() function body


 Braces on the left side {shows the beginning of each function and the one on
the right side} shows the ending of the function.
 All statements in C++ function is delimited in braces and called block.

5. Syntax to direct a program to display the sentence Hello! is located between the
symbol “ “. Keyword endl is used to end the current line and start a new line.

6. Value 0 is returned back to the system as a sign to tell that the program has been
successfully executed. It is not necessary that we should include it in every
program. However, the compiler will display a warning message if there is no
returning value.

MULTIMEDIA UNIVERSITY 3
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

1.4 Object-oriented programming (OOP)

 OOP is a software design methodology.


 The main aspects of OOP is that the programs are defined in terms of “objects”. Each
object contains data and code to manipulate data.
 An object can have a set of values packaged together as a single unit.
 Example: an employee’s name and salary can be considered as a data object.
 Objects in OOP combines:
 States (attributes): in the form of data values that describes the object’s states or
attributes in sufficient detail.
 Behaviour : in the form of functions or methods that operate on the data values and
describe the legal behaviour of the object.
 Example: Real world object- David
 State
I.e. name, address, occupation, salary and marital status
 Behavior
I.e. response to message or stimulus. Example: If David wants to buy a car, he may
consider whether he can afford it considering his salary and family’s expenses
 Example: Software object- Person A
 State: what it contains.
I.e. variables : name, address, IC, nationality, salary, birthdate
 Behavior: What it can do
I.e. methods: calculateAge(), getDetails()
 Objects can be defined as software bundles of data and related methods.
 An object oriented programmer looks at a problem as a system of interacting objects.
 Objects interact by sending messages to one another. Objects can interact without having
to know details of each other’s data or code. It is sufficient to know the type of message
accepted and the type of response returned by the objects.

Example:
Objects: Customer C1 and Account A1
Customer C1 object may send a message to the account A1 object requesting for the
bank balance.

Message Passing

Object 1 Object 2

MULTIMEDIA UNIVERSITY 4
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

Example:
 A type of programming where the programmer can define data types and types of
operations, which will be performed on the data structure.
Example:
Data Types of data

Data Employee No. Integer


Structure Salary float

Types of operation:
Employee No. : Sort employee list based on Employee No.
Salary : Calculate mark.

 By using this method, data structure will become a class such as Employee object,
which consists of data and functions. The programmer can create relationship
between one class with another class such as a class inherits characteristics from
another class. For example, salesperson and Hr manager can inherit the
characteristic from a general class called Employee, which has EmployeeNo and
Salary.

EmpNo.
Salary

Employees

Inherit

Salesperson
HR manager

 In the traditional approach of C programming which is known as procedural programming,


a problem is decomposed into subproblems.
 Due to this process, a collection of functions are created, communicating through
arguments and variables.

MULTIMEDIA UNIVERSITY 5
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

 An object oriented approach identifies the key words or key ideas in the problem and the
relationship between them.
 These key words will be objects in the implementation, describing well defined entities
which will communicate with each other to perform different tasks.
 Example to calculate the salary for a Salesperson, we need to create a sales person
object, S1 that has the attributes such as salary, sales, name, employee no with a
certain values. We can use the functions/ operations such as calc_salary() that performs
some operations on the attributes.

Example :

Suppose there is a need to write a program to keep the record of students in a college. Then
the object for this program will be Student1.

Set of data values : Student_name


Student_address
Student_cgpa

Set of operations : get_name()


get_address()
get_cgpa()

The concept of an object is implemented in C++ using class.


A class is similar to struct type that is often used in C programming.
The difference is that in a class it allows to define both data or variables and also operations
or functions, but in a structure, it only allow the definition of data only.

Example:

STRUCT IN C CLASS IN C++

struct Student Class Student


{ {
char student_name[30]; char student_name[30];
char student_address[100]; char student_address[100];
double student_cgpa; double student_cgpa;
}; void get_name();
void get_address();
void get_cgpa();
};

MULTIMEDIA UNIVERSITY 6
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

1.5 Basic Concept of Object Oriented Programming

(a) Classes
 Class is the blueprint of objects.
 A set of objects that have similar attributes and methods.
 Class is a user defined data type similar to struct type in C programming.
 The variables declared within a class are called data members and the functions
defined within a class are called member functions also known as methods.
 Declaring variables of a specific class type is called creating instances of that
class type, which also can be referred to as objects.
 General format to declare classes:

Class class_name
{
private :
data member variables;
method prototypes();
public :
constructor();
~destructor();
data member variables;
method prototypes();
}

Example :
Example 1 shows the definition of a class Student. Student has attributes such as
name, address, status and others. Same too for the method where it can identify the
status of students whether they have passed or failed.

Example 1

class Student
{
char name[], address[], status[];
int icno, sid; data
double marks;

char DetermineStatus()
{ method
if marks >= 40
status = “Pass”;
else
status = “Fail”;
return status;
}
};

MULTIMEDIA UNIVERSITY 7
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

Example 2

Example 2 shows the definition of a class Box. Every box can have the same
attributes that are width, height and depth. Method needed is to calculate the volume
and area of the box.

class Box
{ double width, height, depth; data

double ComputeVolume()
{ return( width * height * depth );}
method
double ComputeArea()
{ return( width * height ); }
};

(b) Objects
 Object is the term used to explain many things.
 Example: car, bicycle, student, chair and circle.
 An object consists of data and method.
 Properties of an object are called data. In the real world, characteristics of an
object can be divided into two types:
o Data that can be seen such as a human with two hands.
o Data that cannot be seen such as a human with a name.
 Method is a set of function that manipulates data, such as method
DetermineStatus() can determine exam result for object student in Example 1
shown below.

Object : StudentA
Data : name, address, IC number, id, mark, status
Method : DetermineStatus()

Data and method of object: StudentA

Object : Box123
Data : height, depth, width
Method : CalculateVolume()

Data and method of object: Box123

MULTIMEDIA UNIVERSITY 8
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

Classes and objects


 When you create an object of a class (create an instance of a class) it gets its own copy
of state initialized with certain values.

Class Person Person Tom

Variables
Height Height = 178
Weight Weight = 70
Sex Sex = male
name Name = Tom
Methods
M1(…) M1(…)
M2(…) M2(…)
M3(…) M3(…)

Person Andrea

Height = 165
Weight = 51
Sex = female
Name = Andrea

M1(…)
M2(…)
M3(…)

(c) Data Abstraction


 Data abstraction is a process to delete all unnecessary attributes and remain
the necessary attributes to describe an object.
 Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost, and functions to operate on these
attributes.
 Since the classes use the concept of data abstraction, they are known as
Abstract Data Types (ADT). The term abstract data type(ADT) describes any
data type for which the implementation details are kept separate from the logical
properties needed to use it.
 Object in a program is an abstraction from a real object (in real world).
 Attributes  characteristics, which can be seen.
 Behaviours  actions that are done to an object.

MULTIMEDIA UNIVERSITY 9
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

 The figure shown below shows the data abstraction concept in OOP for object
Box.

Class Box

Characteristics
Data abstraction
length Object Length, width, depth
Box

Behaviors
depth
width Calculate_Volume()
Calculate_Area()

(d) Data Encapsulation


 Encapsulation is a principle about hiding the details of the implementation of
the interface.
 It is to reveal as little as possible about the inner workings of the interface.
 Encapsulation hides the details of the process from the user.
 Example, I don’t have to know the internal workings of a microwave in order to
use one.
 The Interface is the implementation code for the external Interface of the
microwave.

 The Implementation is the code that does all the operations, makes the interface
look as if it is doing something. (cook, fry, boil, roast.)
 No part of a complex system should depend on the internal details of another
part.
 Encapsulation is a technique for minimizing interdependencies among modules
by defining a strict external interface.
 This way, internal coding can be changed without affecting the interface, so long
as the new implementation supports the same (or upwards compatible) external
interface.

MULTIMEDIA UNIVERSITY 10
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

 Encapsulation prevents a program from becoming so interdependent that a small


change has massive ripple effects.

 The implementation of an object can be changed without affecting the application


that uses it for:
 Improving performance, fix a bug, consolidate code or for porting.
 Benefits of encapsulation:
o Modularity – the source code for an object can be written and
maintained independently of the source code for other objects.
o Information hiding – object can maintain private information and
methods that it can change at any time without affecting the other objects
that depend on it.

Methods An object's variables make up the center


or nucleus of the object and the methods
surround and usually hide the object's
nucleus from other objects in the
program.
Variables

(e) Inheritance
 Inheritance is the ability to create a new object from an existing one.
 This supports extensibility and reusability within programs.
 In simple terms, it is the ability to define an object based on another and
create a group of objects that related to each other in a hierarchical form.
 When a new object is derived from an existing one, it inherits all properties of the
original object.
 But the new object has the freedom to define it’s own members, thus tailoring its
behaviour to specific needs.
 The base class (super class) represents the generalized model of objects you are
dealing with.
 The derived classes (sub classes) represent specialized objects constructed by
customizing the base class for a specific purpose.
 Each derived class shares common characteristics with the class from which it is
derived.
o Example, cats and dogs are subclasses of a superclass called animals
 The figure below shows the relationship between one and other classes. Derived
class inherits characteristics of the base class

MULTIMEDIA UNIVERSITY 11
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

Class A Base class for B

Derived class from class A Base


Class B
class for class C, D and E

Class C Class D Class E

Derived class from class B

 The figure below shows the concept of Inheritance for class Box.

BOX

Box

Atributes:
Shoes box Cake box
Length
Width
Depth
SHOES BOX CAKE BOX
Behaviours: Atributes: Atributes:
Calculate Volume Length Length
Calculate Area Width Width
Depth Depth
Class Box is a base Brand Type of cake
class
Behaviours: Behaviours:
Calculate Volume Calculate Volume
The bold words are new attributes Calculate Area Calculate Area
and behaviours Display ShoeBrand Display ArtDisplay

Class SHOES BOX and CAKE BOX (derived class) inherit class BOX (base class) where
it has the characteristics and methods from class BOX and add their own characteristics
and methods.

(f) Polymorphism
 Polymorphism is the ability of different objects to respond, each in its unique
way, to identical messages and requests.
 It has the ability to request the same operations to be performed by a wide range
of different things.
 Basically, it means that many different objects can perform the same action.

MULTIMEDIA UNIVERSITY 12
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

 Example, how students respond to school bell. When the bell rings, it has
different meanings to different students. Some go home, some go for another
class, some go to the library, etc.
 Polymorphism simplifies the programming process so that programs can be
written in generic fashion to handle variety of existing and yet to be declared
objects.
 In short, “many methods, one interface”.

Bicycle

Mountain bike Racing bike Tandems

 Consider a method to print all the properties of a bicycle. There will likely be a
different print method for each of the types of bicycles above. By using
polymorphism different methods can be created with the same name but with
different parameters.

1.6 Object-oriented program development life cycle

The object-oriented program development life cycle consists of three main phases:

1. Object-oriented analysis:
This phase is to determine the system requirements and identify objects and their
relationship with other objects. We can also find out the important attributes of
these objects and determine their behaviour and interaction.

2. Object-oriented design:
This phase is a phase to design classes identified during the analysis phase and
user interface.

3. Object-oriented programming (implementation):


This phase will translate the design into actual code.

 Object-oriented analysis and object-oriented design are distinct disciplines, but they
can be intertwined. (See the figure below). For example, you can start with object-

MULTIMEDIA UNIVERSITY 13
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

oriented analysis, model it and create an object-oriented design. If there are any
changes or improvements to be made in a phase you can repeat the first phase
(object oriented analysis), follow by the next phase. This process can be repeated
between phases.

Object-oriented analysis

Object-oriented design

Object-oriented programming
(Implementation)

MULTIMEDIA UNIVERSITY 14
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

 Example of a program, which consists some concepts of object-oriented programming.

#include<iostream.h>
#include<string.h>

class Staff
{
protected:
char name[30], ic[20];
int age;
public:
void set_data(char *a ,char *b, int c) Data abstraction
{ concept
strcpy(name,a);
strcpy(ic,b);
age=c;
}
void show_data() Polymorphism concept
{
cout<<"This is a base class";
}
};

class Executive : public Staff Inheritance concept


{
char position[30];

public:
void set_position(char * a)
{
strcpy(position,a);
}

void show_data() Polymorphism concept


{
cout<<"Name:"<<name<<"\n";
cout<<"IC number:"<<ic<<"\n";
cout<<"Age:"<<age<<"\n";
cout<<"Position:"<<position<<"\n";
}
};

void main()
{
char name[30],ic[20], position[20];
int age;

cout<<"Enter your name:";


cin.getline(name,50);
cout<<"Enter your ic number:";
cin.getline(ic,10);
cout<<"Enter your age:";
cin>>age;
cin.get();
cout<<"Enter your position :";
cin.getline(position,20);
cout<<"\n";

Executive Ex;
Ex.set_data(name,ic,age);
Ex.set_position(position);
Ex.show_data();
}

MULTIMEDIA UNIVERSITY 15
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

1.7 Advantages of object-oriented programming

Object-oriented programming offers many advantages. Among the advantages are it can
solve program problems and also increase productivity. Below are advantages of object-
oriented programming:

(a) Code extensibility


 Ability to add codes, which are already existing and consistent with, needs.
 It is more suitable for a new program.
Example: A VCR remote control functions the same way as the new VCR, which will be
used in the future.

(b) Code reusability


 Existing code can be tested first before it is inherited from previous module.
 This will save cost and time needed to develop software.
 With this method, it will help to increase programmer’s productivity.

(c) Represent real world

 Using object-oriented concept, it will assist the programmer in creating a module because
data used represents real situations.
 Thus, difficulties in developing software can be reduced.

(d) Data security


 The use of encapsulation concept has made data to be protected from misuse by an
unauthorized person.

1.8 Differences between Procedural Programming and Object-Oriented Programming


• In procedural language (Like C or Pascal)
– You create a program by determining:
• The task you want your program to accomplish
• Then figuring out the steps or procedures that are needed to accomplish
the task.
• The code is organized into several functions, and each function typically
represents a sub-task.
• In object oriented language (Like C++ or JAVA)
– You create a program by determining:
• First, what objects the program will use to accomplish its goal.
• For each kind of object, you determine what data the object needs to
contain, and what messages the object should respond to.

MULTIMEDIA UNIVERSITY 16
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

No: Procedural Programming Object-oriented Programming


1 Definition of function Definition of function
- Using scope of variable
void EnterData()
{…….} void Person::enterData(char *a, int b)
void showData(char *a, int b) {…….}
{…….} void Person::showData( )
{…….}
2 Based on functions defined by the Programming technique based on object.
users.
The use of the encapsulation concept to
Dividing a large program into several combine data and function into one component.
functions. Each function will perform (Class)
a specific task.
Example:
Example: class Individual{
void main( ){ ……….. // data
……….. void Personal( )
Personal (name,age); };
} main( ){
void Personal(char *a, int b) Individual a;
{ /* Definition of Personal function */ /*Object a access data and method from class
}
Individual */
}
3 Program code cannot be used Allow code reusability
multiple times
It can be done by using the inheritance
Each function is assigned to a technique. This technique allows the object to
specific task. We must accept the inherit data and functions from other objects.
function as what is written. To modify
it, the code must be copied again
and changed to meet the program Example:
needs. We use a radio for home usage, which also can
be used as a car radio and at the beach.
Example:
We have designed a radio for home
usage. The technology can be used
to design car radio or radio which
can be used at the beach.

MULTIMEDIA UNIVERSITY 17
DCS 5088 OBJECT ORIENTED PROGRAMMING LECTURE 1

4 Function which manipulate data Use encapsulation to act on data

Data (e.g: name, age) will be passed to Encapsulation is used to package data and
other functions (e.g: print, display, add method together. It identifies the functions,
and delete) to be manipulated. The which will act on each object. The class will
function in which will manipulate the control any operations on data and function
data is not defined yet. inside it.

5 No access control for data Limitations to access data

Main() function can access all data and There are access controls for data in a
functions in a program. class. For example: keyword private and
protected. To access private data it must be
done through method or encapsulation
mechanism.

6 Does not support polymorphism Support polymorphism

References:
1. Gary Bronson, Object-Oriented Program Development Using C++: A Class-Centered
Approach, Thomson Course Technology, 2005
2. Richard Johnsonbaugh, Martin Kalin, Object-oriented programming in C++, 2/e,
Prentice Hall, 2000

MULTIMEDIA UNIVERSITY 18

You might also like