Title: CS2203 OBJECT ORIENTED PROGRAMMING 3 0 0 3
1CS2203 OBJECT ORIENTED PROGRAMMING
3 0 0 3
-
(Common to CSE IT) - Aim
- To understand the concepts of object-oriented
programming and master OOP using C. - 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
2Unit 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
3Objects
- 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
4Classes
- 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.
5classes
- 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.
6Problem 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 ltltrollno
- cout ltltname
- cout ltlt address
-
-
7TV-01 Class and 3 Instances
8Object-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
9Encapsulation
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()
10Example Code
class Rect private int width,
length public Rect (int w, int l)
width w length l int
compute_area() return widthlength
main() Rect rect1(3,5) int
x xrect1.compute_area() coutltltxltltendl
11Methods 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
12- 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
13(No Transcript)
14Characteristics 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
15O-O Principles and C Constructs
- O-O Concept C Construct(s)
- Abstraction Classes
- Encapsulation Classes
- Information Hiding Public and Private Members
- Polymorphism Operator overloading,
- templates, virtual functions
- Inheritance Derived Classes
16OOP Features
- 4 major features in OOP
- encapsulation
- information hiding
- inheritance
- overloading
17Encapsulation
- 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
18Information 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
19Why 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
20Inheritance
- 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.
21Inheritance (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
22Overloading
- 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.
23Why 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
24- 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 unit2.
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.
25Abstract Types
class Shape public Shape() //
Calculate the area for // this shape virtual
int compute_area() 0
26ABSTRACTION 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
27- Advantages of Data Abstraction and
- Data Encapsulation
- ?? Simplification of software development
- ?? Testing and Debugging
- ?? Reusability
- ?? Modifications to the representation of a data
type
28Abstract 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
29Florida 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
Mortgage
Loan
29 of 10 slides
COP 2551 Object-Oriented Programming OO
Concepts Overview
30Florida 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.
A Class
Public variables and methods
Private variables and methods
Public variables is not recommended
30 of 10 slides
COP 2551 Object-Oriented Programming OO
Concepts Overview
31- 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
32Inheritance 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
33INTRODUCTION TO C
- Inherit all ANSI C directives
- Inherit all C functions
34Basic 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 ltiostream.hgt)
- cout ltlt Hello"
- char name10
- cin gtgt name
- cout ltlt Hi, " ltlt name ltlt ", nice name." ltlt endl
- cout ltlt endl // print a blank line
- declaring variables almost anywhere
- // declare a variable when you need it
- for (int k 1 k lt 5 k)
-
- char am
- cout ltlt k ltlt a
-
35CLASSES
36A Graphical Representation of Classes
the Dog class
the Person class
attributes (data component)
colour name where
name own
interface to the outside world
walk instruct write_email
walk swim bark
methods (procedural component)
37A Graphical Representation of Objects
Paki, a Dog object
Lassie, a Dog object
Ravi, a Person object
colour yellow name Paki where xxx
colour white/brown name Lassie where Annur
name Ravi own Lassie
walk swim bark
walk instruct write_email
walk swim bark
, another Dog object
Raja, a Person object
nameRaja own null
, another Dog object
, another Person object
walk instruct write_email
38Access 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.
39- Class student
-
- Public
- int RollNo
- private
- string name
- string address
- public
- void PrintDetails()
-
- cout ltltrollno
- cout ltltname
- cout ltlt address
-
-
- void main()
- student student1
40Function and data member
- 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.
41- Class student //defining function
members outside class -
- Public
- int RollNo
- string name
- string address
- void PrintDetails() //prototype
-
-
- void student PrintDetails()
-
- cout ltltrollno
- cout ltltname
- cout ltlt address
-
-
- void main()
- student student1
42 - class student
- public
- static int PassingMark
- int SubjectMark5 bool fail
- void DisplayMarks()
- for (int i0ilt5i)
- cout ltltMarks of subject
No. - cout ltltiltltis
ltltSubjectMarki -
-
- void SetMarks (int Marks5
- for (int i0 ilt5 i)
-
SubjectMarksiMarksi -
-
- bool CheckPassing()
- failfalse
- for (int i0ilt5 i)
- if (SubjectMarkiltPassi
ngMark)
43- int student PassingMark
- //required definition
- void main()
-
- studentPassingMark35
- student X
- student Y
- int Xmarks75,55,65,56,89
- int Ymarks15,25,100,98,89
- X.SetMarks(Xmarks)
- Y.SetMarks(Ymarks)
- X.CheckPassing()
- Y.CheckPassing()
-
44Default 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,)
45Default Arguments (Examples)
- 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
double pow(double x, int n2) // computes and
returns xn
46Default 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 y0, int n) // illegal
int f(int x, int y0, int n1) // legal
47Function 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.
48Function Overloading
- Two or more functions can have the same name but
different parameters - Example
int max(int a, int b) if (agt b) return
a else return b
float max(float a, float b) if (agt b) return
a else return b
49- 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.
50Friend function
- class class1privateint numpublicvoid
get()coutltlt"Number"cingtgtnumfriend void
display(class1 cl)void display(class1
c1)coutltltC1.NUMint main()class1
clscls.get()display(cls)
51- //static member friend function matrix
multiplication - Â
- includeltiostream.hgt
- includeltconio.hgt
- Â
- class matrixvector
-
- static int a33
- static int b3
- static int c3
- public
- void getmatrix(void)
- void getvector(void)
- friend int multiply(matrixvector mv)
-
- Â
- int matrixvectora33
- int matrixvectorb3
- int matrixvectorc3
52- void matrixvectorgetvector(void)
-
- coutltlt"\n"
- coutltlt"\n enter the vector "
- for(int k0 klt3k)
-
- cingtgtbk
-
-
- Â
- int multiply(matrixvector mv)
-
- coutltlt"matrix - vector multiplication \n"
- coutltlt"\n the vector \n"
- Â
- for(int m0mlt3m)
-
- coutltlt"\n"
- coutltltmv.bm
53- coutltlt"\n"
-
- for(int e0elt3e)
-
- for(int d0dlt3d)
-
- mv.cemv.cemv.aedmv.bd
-
- coutltlt"\n the result is \n"
- for(int n0nlt3n)
-
- coutltltmv.cn
- coutltlt"\n"
-
- return 0
-
- Â int main()
-
- clrscr()
54const 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.
55- void PrintDetails()const
-
- cout ltltrollno
- cout ltltname
- cout ltlt address
- rollno4 //error
-
- If rollno definition is changed to
- mutable int rollno
- in the student class ,then there will not be an
error.
56Volatile 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.
57- 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.
58Pointers and objects
int x 10 int p p x p gets the
address of x in memory.
p
x
10
59What is a pointer?
int x 10 int p p x p 20 p is
the value at the address p.
p
x
20
60What is a pointer?
Declares a pointer to an integer
int x 10 int p NULL p x p 20
is address operator gets address of x
dereference operator gets value at p
61Allocating 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.
62Deallocating 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.
63Using new with arrays
- int x 10
- int nums1 new int10 // ok
- int nums2 new intx // ok
- Initializes an array of 10 integers on the heap.
64- 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-gtgetdata()
-
ptr-gt 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 student5
65constant 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 ltltrollno
- cout ltltname
- cout ltlt address
66nested 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.
67local 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.
68Basic 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 /
69C - 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
70Take 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.