Sie sind auf Seite 1von 70

CS2203 OBJECT ORIENTED PROGRAMMING

(Common to CSE & IT)


Aim: To understand the concepts of object-oriented programming and master OOP using C++.

3003

Unit I 9 Object oriented programming concepts objects classes methods and messages abstraction and encapsulation inheritance abstract classes polymorphism. Introduction to C++ classes access specifiers function and data members default arguments function overloading friend functions const and volatile functions static members Objects pointers and objects constant objects nested classes local classes Unit II 9 Constructors default constructor Parameterized constructors Constructor with dynamic allocation copy constructor destructors operator overloading overloading through friend functions overloading the assignment operator type conversion explicit constructor Unit III 9 Function and class templates - Exception handling try-catch-throw paradigm exception specification terminate and Unexpected functions Uncaught exception. Unit IV 9 Inheritance public, private, and protected derivations multiple inheritance virtual base class abstract class composite objects Runtime polymorphism virtual functions pure virtual functions RTTI typeid dynamic casting RTTI and templates cross casting down casting . Unit V ` 9 Streams and formatted I/O I/O manipulators - file handling random access object serialization namespaces - std namespace ANSI String Objects standard template library. Total: 45 TEXT BOOKS: 1. B. Trivedi, Programming with ANSI C++, Oxford University Press, 2007. REFERENCES: 1. Ira Pohl, Object Oriented Programming using C++, Pearson Education, Second Edition Reprint 2004.. 2. S. B. Lippman, Josee Lajoie, Barbara E. Moo, C++ Primer, Fourth Edition, Pearson Education, 2005. 3. B. Stroustrup, The C++ Programming language, Third edition, Pearson Education, 2004.

Unit I
Object oriented programming concepts objects classes methods and messages abstraction and encapsulation inheritance abstract classes polymorphism. Introduction to C++ classes access specifiers function and data members default arguments function overloading friend functions const and volatile functions static members Objects pointers and objects constant objects nested classes local classes

Objects
An object is an encapsulation of both functions and data
Objects are an Abstraction represent real world entities Classes are data types that define shared common properties or attributes Objects are instances of a class All objects have attributes (characteristics), this is sometimes referred to as state. Objects have State have a value at a particular time Objects have Operations associated set of operations called methods that describe how to carry out operations (behavior) Objects have Messages request an object to carry out one of its operations by sending it a message messages are the means by which we exchange data between objects

Classes
Class : Whatever we can see in this world all the things are a object. And all the objects are categorized in a special group. That group is termed as a class. Class has many other features like creation and implementation of the object, Inheritance etc.

classes
Every object belongs to (is an instance of) a class An object may have fields, or variables
The class describes those fields

An object may have methods


The class describes those methods

An Abstract Data Type (ADT) bundles together:


some data, representing an object or "thing" the operations on that data

The operations defined by the ADT are the only operations permitted on its data Example: a CheckingAccount, with operations deposit, withdraw, getBalance, etc.

Problem: printing student mark sheet


Class student Real world entities: student, teacher, subject, mark sheet etc. Class student { Public : int RollNo; string name; string address; void PrintDetails() { cout <<rollno; cout <<name; cout << address; } };

TV-01 Class and 3 Instances

Object-Oriented Concept
The rectangle area problem Define a class: Rect
Data: width, length Functions: compute_area()

An object: an instance of the class Rect


To Solve the problem, create an object of Rect, and request this object to return the area of the rectangle

Encapsulation
class Circle { private: int radius public: Circle(int r); // The area of a circle int compute_area(); }; }; class Triangle { private: int edgea, edgeb, edgec; public: Triangle (int a, int b, int c); // The area of a triangle int compute_area();

Example Code
class Rect { private: int width, length; public: Rect (int w, int l) { width = w; length = l; } int compute_area() { return width*length; } }

main() { Rect rect1(3,5); int x; x=rect1.compute_area(); cout<<x<<endl; }

Methods & Messages


Sending a message is our way of:
interacting with objects. manipulating an objects state. Tells the object what to do with itself Example: To change the channel on TV We use the channel selection buttons ,This sends a message that we want to select a new channel The TV responds to the message by selecting and executing a method. The TV now receives a new signal which is the channel we selected

Method Tells the object how to respond to a message Our TV-01 objects respond to the following messages: Turn the television set on or off Change the channel Change the volume

Characteristics of OOPL
Encapsulation: Combining data structure with actions
Data structure: represents the properties, the states, or characteristics of objects Actions: permissible behaviors that are controlled through the member functions

Data hiding: Process of making certain data inaccessible

Inheritance: Ability to derive new objects from old ones


permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more general/base class ability to define a hierarchical relationship between objects

Polymorphism: Ability for different objects to interpret functions


differently

O-O Principles and C++ Constructs


O-O Concept
Abstraction Encapsulation Information Hiding Polymorphism Inheritance

C++ Construct(s)
Classes Classes Public and Private Members Operator overloading, templates, virtual functions Derived Classes

OOP Features
4 major features in OOP
encapsulation information hiding inheritance overloading

Encapsulation
an object encapsulates both its attributes & methods implications:
an attribute/ method is attached to an object/ class when you mention an attribute/ methods, you have to specify which object/ class it comes from

why encapsulation?
when you get hold of an object, you also get hold of its data & behaviour components good for reuse

Information Hiding
an object can hide its internal details
e.g. you dont know how your mobiles electronics works except punching the buttons

can selectively show some details to the outside world


e.g. your mobile only shows the number it dials

defines an interface to interact with the outside world


e.g. your mobile interacts with your through the buttons & screen

Why Information Hiding?


the object can have a complex internal but simple interface
making interaction with the outside world easier

you dont need to know about the internal of an object


only the interface is important i.e. how to interact with it

facilitate code reuse


hiding any internal change from the outside world by keeping the interface unchanged

Inheritance
a class may be similar to another class but being more specialised
e.g. the class student is similar to the class person but student is more specialised
a person has attributes like: sex, age, name a student has all these + a student no.

Inheritance (contd)
a subclass
extends/ specialises a superclass inherits attributes & methods from its superclass may have more attributes/ methods than its superclass may change the content/ procedure of an inherited method
i.e. same method name/ signature but different behaviour

why inheritance?
reuse existing class definition customise/ specialise if needed

Overloading
different functions/ procedures/ methods can have the same name
provided that the parameters are of different types
giving a unique signature

the system will figure out which one to invoke e.g. you can have 2 procedures, both named call, taking a dog or person object as parameter respectively. Depending on you give it a dog or person object as the parameter, Java will know which one to use.

Why Overloading?
you can call the same method (name) but invoke different behaviour
dynamic binding of method
which method to invoke is determined at runtime

code reuse
in term of the calling code

Encapsulation is the mechanism that binds together code and data, and keeps both safe from outside interference or misuse. 1. Both data and member functions treated as single unit 2. Abstract focuses on behavior of object, encapsulation focuses on actual implementation 3. Encapsulation achieved through data hiding 4. For abstractions to work, implementations must be encapsulated.

Abstract Types
class Shape { public: Shape();

// Calculate the area for // this shape virtual int compute_area() = 0;


};

ABSTRACTION AND ENCAPSULATION


Definition: Data Encapsulation or Information Hiding is the concealing of the implementation details of a data object from the outside world. Definition: Data Abstraction is the separation between the specification of a data object and its implementation. Definition: A data type is a collection of objects and a set of operations that act on those objects. Definition: An abstract data type (ADT) is a data type that is organized in such a way that the specification of the objects and the specification of the operations on the objects is separated from the representation of the objects and the implementation of the operation

Advantages of Data Abstraction and Data Encapsulation Simplification of software development Testing and Debugging Reusability Modifications to the representation of a data type

Abstract Classes

May Contain abstract methods Some methods and data may be defined abstract class ColouredShape { private Colour c; // storage allocated for each public abstract void draw(); public Colour getColour() { return c; } public abstract void erase(); } No instances allowed Subclasses must implement all abstract methods or they are also abstract

Florida Community College at Jacksonville

Object-oriented Principle Inheritance


Inheritance is the process by which one object acquires the properties of another object. By use of inheritance, an object need only define all of its characteristics that make it unique within its class, it can inherit its general attributes from its parent.
Account Checking
COP 2551 Object-Oriented Programming

Mortgage

Loan
29 of 10 slides

OO Concepts Overview

Florida Community College at Jacksonville

Object-oriented Principle Encapsulation


Encapsulation is the mechanism that binds together the code and the data it manipulates, and keeps both safe from outside interference and misuse.
Public variables and methods Private variables and methods Public variables is not recommended
COP 2551 Object-Oriented Programming OO Concepts Overview 30 of 10 slides

A Class

Encapsulation Hides the implementation details of a class Forces the user to use an interface to access data Makes the code more maintainable API doc as an example

Inheritance and Polymorphism


class Circle : public Shape { private: int radius; public: Circle (int r); int compute_area(); }; class Triangle : public Shape { private: int edgea, edgeb, edgec; public: Triangle (int a, int b, int c); int compute_area(); };

int sum_area(Shape s1, Shape s2) {


return s1.compute_area() + s2.compute_area(); // Example of polymorphism }

INTRODUCTION TO C++
Inherit all ANSI C directives Inherit all C functions

Basic C++ Extension from C

comments
/* You can still use the old comment style, */ /* but you must be very careful about mixing them */ // It's best to use this style for 1 line or partial lines /* And use this style when your comment consists of multiple lines */

cin and cout (and #include <iostream.h>)


cout << Hello"; char name[10]; cin >> name; cout << Hi, " << name << ", nice name." << endl; cout << endl; // print a blank line

declaring variables almost anywhere


// declare a variable when you need it for (int k = 1; k < 5; k++) { char a=m; cout << k << a;

CLASSES

A Graphical Representation of Classes


the Dog class the Person class name own walk instruct write_email attributes (data component) interface to the outside world colour name where walk swim bark

methods (procedural component)

A Graphical Representation of Objects


Paki, a Dog object

Ravi, a Person object


name: Ravi own: Lassie walk instruct write_email
Raja, a Person object
name:Raja own: null walk instruct write_email

Lassie, a Dog object


colour: white/brown name: Lassie where: Annur walk swim bark
colour: yellow name: Paki where: xxx walk swim bark

, another Dog object

, another Person object

, another Dog object

Access specifiers
Specify whether the data defined will be available to the users of the objects of the class. Public Private Protected Public: the data defined under public is available to objects. Private: data defined under private is not available to objects.

Class student { Public : int RollNo; private: string name; string address; public: void PrintDetails() { cout <<rollno; cout <<name; cout << address; } }; void main() { student student1; student1.RollNo= 7; student1.name= X; // does not work since name is private student1.address= Y; // does not work since name is private Student1.PrintDetails(); }

Function and data member


1. 2. 1. 2. 3. Functions can be defined either inside or outside the class. Defining function members outside class very simple to define functions outside class If the functions are bigdefine outside Static data members of class Static members are stored at a location where they are retained throughout the execution of the program and are not stored with class objects. Stored only as a single copy similar to member functions. All the static data members are initialized to zero at the time of declaration.

Class student //defining function members outside class { Public : int RollNo; string name; string address; void PrintDetails(); //prototype };

void student :: PrintDetails() { cout <<rollno; cout <<name; cout << address; } }; void main() { student student1; student1.RollNo= 7; student1.name= X; student1.address= Y; Student1.PrintDetails();
}

class student { public: static int PassingMark; int SubjectMark[5]; bool fail; void DisplayMarks() { for (int i=0;i<5;++i) , cout <<Marks of subject No.; cout <<i<<is <<SubjectMark*i+; } } void SetMarks (int Marks[5] { for (int i=0; i<5; ++i) { SubjectMarks[i]=Marks[i]; } } bool CheckPassing() { fail=false; for (int i=0;i<5; ++i) { if (SubjectMark[i]<PassingMark) fail= true; } if (fail) cout << congratulations! You are passing\n; else cout <<sorry ! You are failing\n; return !fail; }};

int student:: PassingMark; //required definition void main() { student::PassingMark=35; student X; student Y; int Xmarks[]={75,55,65,56,89}; int Ymarks[]={15,25,100,98,89}; X.SetMarks(Xmarks); Y.SetMarks(Ymarks); X.CheckPassing(); Y.CheckPassing(); }

Default Arguments
A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call. Syntax: return_type f(, type x = default_value,);

Default Arguments (Examples)


double pow(double x, int n=2) // computes and returns xn The default value of the 2nd argument is 2. This means that if the programmer calls pow(x), the compiler will replace that call with pow(x,2), returning x2

Default Arguments (Rules)


Once an argument has a default value, all the arguments after it must have default values. Once an argument is defaulted in a function call, all the remaining arguments must be defaulted.
int f(int x, int y=0, int n) // illegal int f(int x, int y=0, int n=1) // legal

Function overloading
Function redefined with different set of arguments. EX: add(float, float) Add(int, int) Add (int, int, int) Function overloading is useful when similar function is required to be called with either variable number of arguments or arguments of different type or both.

Function Overloading
Two or more functions can have the same name but different parameters Example:
int max(int a, int b) { if (a>= b) return a; else return b; } float max(float a, float b) { if (a>= b) return a; else return b; }

What is a Friend Function? A friend function is used for accessing the non-public members of a class. A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. How to define and use Friend Function in C++: The friend function is written as any other normal function, except the function declaration of these functions is preceded with the keyword friend. The friend function must have the class to which it is declared as friend passed to it in argument. Some important points The keyword friend is placed only in the function declaration of the friend function and not in the function definition. It is possible to declare a function as friend in any number of classes. When a class is declared as a friend, the friend class has access to the private data of the class that made this a friend.

It is possible to declare the friend function as either private or public.


The function can be invoked without the use of an object.

class class1 { private: int num; public: void get() { cout<<"Number:"; cin>>num; } friend void display(class1 cl); }; void display(class1 c1) { cout<<C1.NUM; } int main() { class1 cls; cls.get(); display(cls); }

Friend function

//static member friend function matrix multiplication #include<iostream.h> #include<conio.h> class matrixvector { static int a[3][3]; static int b[3]; static int c[3]; public: void getmatrix(void); void getvector(void); friend int multiply(matrixvector mv) };

int matrixvector::a[3][3]; int matrixvector::b[3]; int matrixvector::c[3];


void matrixvector::getmatrix(void) { cout<<"\n enter the matrix value \n"; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { cin>>a[i][j]; } } }

void matrixvector::getvector(void) { cout<<"\n"; cout<<"\n enter the vector :"; for(int k=0; k<3;k++) { cin>>b[k]; } } int multiply(matrixvector mv) { cout<<"matrix - vector multiplication \n"; cout<<"\n the vector \n"; for(int m=0;m<3;m++) { cout<<"\n"; cout<<mv.b[m]; } cout<<"\n the matrix \n"; for(int i=0;i<3;i++) { for (int j=0; j<3; j++) { cout<<mv.a[i][j]; cout<<"\t"; }

cout<<"\n"; } for(int e=0;e<3;e++) { for(int d=0;d<3;d++) { mv.c[e]=mv.c[e]+mv.a[e][d]*mv.b[d]; }} cout<<"\n the result is \n"; for(int n=0;n<3;n++) { cout<<mv.c[n]; cout<<"\n"; } return 0; } int main() { clrscr(); matrixvector mv; mv.getvector(); mv.getmatrix(); multiply(mv); getch(); return 0;}

const member functions


A function, which guarantees not to modify the invoking object. If the body of the const function contains a statement that modifies the invoking object, the program does not compile. One exception here is the mutable member. A mutable data member can be modified by const function.

void PrintDetails()const { cout <<rollno; cout <<name; cout << address; rollno=4 //error } If rollno definition is changed to mutable int rollno; in the student class ,then there will not be an error.

Volatile functions
A member function invoked by a volatile object. A volatile object s value can be changed by external parameters which are not under the control of the program.

volatile member functions. Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object: class B { int x; public: void f() volatile; // volatile member function }; int main() { volatile B b; // b is a volatile object b.f(); // call a volatile member function safely } The object b is declared volatile. Calling a non-volatile member function from this object is unsafe, because b's state might have been changed by a different thread in the meantime. To ensure that f() can be called safely for a volatile object, it's declared volatile too.

Pointers and objects


int x = 10; int *p; p = &x;

10

p gets the address of x in memory.

What is a pointer?
int x = 10; int *p; p = &x; *p = 20;

20

*p is the value at the address p.

What is a pointer?
int x = 10; int *p = NULL; p = &x; *p = 20; Declares a pointer to an integer & is address operator gets address of x

* dereference operator gets value at p

Allocating memory using new


Point *p = new Point(5, 5); new allocates space to hold the object. new calls the objects constructor. new returns a pointer to that object.

Deallocating memory using delete


// allocate memory Point *p = new Point(5, 5); ... // free the memory delete p; For every call to new, there must be exactly one call to delete.

Using new with arrays


int x = 10; int* nums1 = new int[10]; int* nums2 = new int[x];

// ok // ok

Initializes an array of 10 integers on the heap.

A pointer can point to an object created by a class. Object pointers are useful in creating objects at run time. student s1; student *ptr = &s1; s1. getdata(); s1.show(); equivalent to ptr->getdata(); ptr-> show(); or (*ptr).show(); we can also create the objects using pointers and new operator student *ptr = new student; This allocates enough memory for the data members in the object structure and assigns the address of the memory space to ptr. We can also create an array of objects using pointers. student *ptr = new student[5];

constant objects
const student s1(x,y); // object s1 is constant Any attempt to modify the values of x and y will generate compile time error. A constant object can call only constant member functions. void PrintDetails()const { cout <<rollno; cout <<name; cout << address; }

nested classes
It is an another way of inheriting properties of one class into another. From this we can understand that an object can be collection of many other objects, that is a class can contain objects of other classes as its members . class alpha(); class beta(); class gamma { alpha a1; beta b1; }; All objects of gamma class will contain the objects a1 and b1. This kind of relationship is called containership or nesting.

local classes
Classes can be defined and used inside a function or a block. Such classes are called local classes. void test(int a) //function { .. class student //local class {.. .. //class definition -; student s1(a); //create student object . } Local classes can use global variables and static variables declared inside the function. Enclosing function cannot access the private member of a local class.

Basic C++ Extension from C (II)


const
In C,#define statements are handled by the preprocessor, so there is no type checking. In C++, the const specifier is interpreted by the compiler, and type checking is applied.

New data type


Reference data type &. Much likes pointer int ix; /* ix is "real" variable */ int & rx = ix; /* rx is "alias" for ix */ ix = 1; /* also rx == 1 */ rx = 2; /* also ix == 2 */

C++ - Advance Extension


C++ allow function overloading
In C++, functions can use the same names, within the same scope, if each can be distinguished by its name and signature The signature specifies the number, type, and order of the parameters The name plus signature, then, uniquely identifies a function

Take Home Message


There are many different kinds of programming paradigms, OOP is one among them. In OOP, programmers see the execution of the program as a collection of dialoging objects. The main characteristics of OOPL include encapsulation, inheritance, and polymorphism. Not only OOPL can do OOP, but also others.