Anda di halaman 1dari 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

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

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 objectoriented 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

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

1.3 Example of first C++ program


This program will display the sentence Hello!.

//First C++ program #include <iostream.h> int main() { cout<<Hello!<<endl; return 0; }

(1) Comment (2) pre-processor directive (3) function header (5) display instruction

(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

MULTIMEDIA UNIVERSITY

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

program. However, the compiler will display a warning message if there is no returning value.

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 employees 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 objects 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 familys 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 others 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.

MULTIMEDIA UNIVERSITY

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

Message Passing

Object 1

Object 2

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 Data Structure Employee No. Salary Types of data Integer 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
MULTIMEDIA UNIVERSITY 5

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

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. 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 struct Student { char student_name[30]; char student_address[100]; double student_cgpa; }; CLASS IN C++ Class Student { char student_name[30]; char student_address[100]; double student_cgpa; void get_name();
6

MULTIMEDIA UNIVERSITY

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

void get_address(); void get_cgpa(); };

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; double marks; char DetermineStatus() { if marks >= 40 status = Pass; else status = Fail; return status; } }; MULTIMEDIA UNIVERSITY 7

data method

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; double ComputeVolume() { return( width * height * depth );} double ComputeArea() { return( width * height ); }; }

data method

(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 o Data that can be seen such as a human with two hands. 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 Data : StudentA : name, address, IC number, id, mark, status

Method : DetermineStatus() Data and method of object: StudentA Object Data Method : Box123 : height, depth, width : CalculateVolume()

MULTIMEDIA UNIVERSITY

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

Data and method of object: Box123

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 Variables Height Weight Sex name Methods M1() M2() M3() Person Tom

Height = 178 Weight = 70 Sex = male Name = Tom M1() M2() 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

MULTIMEDIA UNIVERSITY

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

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. The figure shown below shows the data abstraction concept in OOP for object Box.

Class Box Characteristics Data abstraction length


Object Box

Length, width, depth

Behaviors width depth 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 dont 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.
MULTIMEDIA UNIVERSITY

10

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

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. 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 o Modularity the source code for an object can be written and maintained independently of the source code for other objects. 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 its 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.

MULTIMEDIA UNIVERSITY

11

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

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

Class A

Base class for B

Class B

Derived class from class A Base 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: Length Width Depth Behaviours: Calculate Volume Calculate Area Class Box is a base class
The bold words are new attributes and behaviours

Shoes box
SHOES BOX Atributes: Length Width Depth Brand Behaviours: Calculate Volume Calculate Area Display ShoeBrand

Cake box
CAKE BOX Atributes: Length Width Depth Type of cake Behaviours: Calculate Volume Calculate Area 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.

MULTIMEDIA UNIVERSITY

12

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

(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. 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):


MULTIMEDIA UNIVERSITY

13

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

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 objectoriented 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 Object-oriented analysis analysis

Object-oriented Object-oriented design design

Object-oriented Object-oriented programming programming (Implementation) (Implementation)

MULTIMEDIA UNIVERSITY

14

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

Example of a program, which consists some concepts of objectoriented 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) { strcpy(name,a); strcpy(ic,b); age=c; } void show_data() { cout<<"This is a base class"; } }; class Executive : public Staff { 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; MULTIMEDIA UNIVERSITY Ex.set_data(name,ic,age); Ex.set_position(position); Ex.show_data(); }

Data abstraction concept

Polymorphism concept

Inheritance concept

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 objectoriented 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 programmers 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.

MULTIMEDIA UNIVERSITY

16

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

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.

No: 1

Procedural Programming Definition of function


void EnterData() {.} void showData(char *a, int b) {.}

Object-oriented Programming Definition of function - Using scope of variable


void Person::enterData(char *a, int b) {.} void Person::showData( ) {.}

Based on functions defined by the 2 users.

Programming technique based on object. The use of the encapsulation concept to

Dividing a large program into several functions. Each function will perform a specific task.

combine data and function into one component. (Class) Example:

Example: void main( ){ .. Personal (name,age); } void Personal(char *a, int b) { /* Definition of Personal function */ } Program code cannot be used 3 multiple times

class Individual{ .. // data void Personal( ) }; main( ){ Individual a; /*Object a access data and method from class Individual */ } Allow code reusability It can be done by using the inheritance

Each function is assigned to a specific task. We must accept the function as what is written. To modify it, the code must be copied again and changed to meet the program needs. Example: We have designed a radio for home usage. The technology can be used be used at the beach.

technique. This technique allows the object to inherit data and functions from other objects.

Example: We use a radio for home usage, which also can be used as a car radio and at the beach.

MULTIMEDIA UNIVERSITY

to design car radio or radio which can

17

DCS 5088 OBJECT ORIENTED PROGRAMMING

LECTURE 1

Function which manipulate data Data (e.g: name, age) will be passed to other functions (e.g: print, display, add and delete) to be manipulated. The function in which will manipulate the data is not defined yet.

Use encapsulation to act on data Encapsulation is used to package data and method together. It identifies the functions, which will act on each object. The class will control any operations on data and function inside it. Limitations to access data There are access controls for data in a class. For example: keyword private and protected. To access private data it must be done through method or encapsulation mechanism.

No access control for data Main() function can access all data and functions in a program.

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

Anda mungkin juga menyukai