OBJECT ORIENTED PROGRAMMING - PowerPoint PPT Presentation

1 / 78
About This Presentation
Title:

OBJECT ORIENTED PROGRAMMING

Description:

Microsoft C /Turbo C - Lafore. C How to program Deitel, Third edition ... 'compute-tax', 'print-pay-slip' Object Oriented Programming. Abstraction (Contd... – PowerPoint PPT presentation

Number of Views:7018
Avg rating:3.0/5.0
Slides: 79
Provided by: bap2
Category:

less

Transcript and Presenter's Notes

Title: OBJECT ORIENTED PROGRAMMING


1
OBJECT ORIENTED PROGRAMMING IN C
July 19, 2004 Elizabeth Sherly
2
Objective
  • A crash programme on C and thorough
    understanding of object-oriented concepts
  • Write C programs using C concepts
  • Get a better understanding of solving problems
    using C

3
Goal
  • Upon the completion of the session, you should be
    able to know
  • Structured Programming Object Oriented
    Programming
  • Software Retrospection and Need of OOPs
  • OOPs- Characteristics
  • Classes and Objects

4
References
  • Programming in C Third edition Bjarne
    Stroustrup
  • Microsoft C/Turbo C - Lafore
  • C How to program Deitel, Third edition
  • Object Oreinted Programming with C, Balagurusamy

5
C
  • C is a generic programming language, developed
    by Bjarne Stroustrup in early 80s at AT T Lab.
  • It is better than C
  • Object Oriented Programming
  • More appropriate for commercial application and
    system programming

6
Software Crisis
Retrospection Software Crisis of 1970s,
characterized by
  • poor quality and reliability
  • time and cost overruns
  • user dissatisfaction

Cause identified as
  • inherent complexity of software and
  • CABTAB (Code A Bit, Test A Bit) approach towards
  • development

7
Retrospection (Contd..)
  • Real world entities
  • Open Interface
  • Reusability and extensibility
  • Tolerant to any changes in future
  • Productivity and decrease software cost
  • Quality of software
  • Time Schedules
  • Software Development process

8
Retrospection (Contd.)
  • Software Engineering advocated closer attention
    to
  • various stages of development such as
    Requirements
  • Analysis, Design,Coding and Testing and many
    models
  • of sequencing these activities were suggested
  • Application of Software Engineering principles
  • progressively improved chances of
  • Delivery as per schedule
  • Customer satisfaction
  • Change management
  • Re-use

9
Object Oriented Programming
Need for a paradigm shift
  • Complexity of applications and environments is
  • rapidly increasing
  • Eg. Programs need to work on many platforms, and
  • hence require abstraction for networking and also
    for
  • inter-operating dynamically with other software
    on
  • these computers)

10
Procedural verses Object Oriented
  • Emphasis on Functions
  • Programs are divided into functions
  • Share Global data
  • Functions transform data
  • Top down Approach
  • Emphasis on Data
  • Programs are divided into Objects
  • Data is hidden and highly protected
  • Objects communicate each other using functions
  • Bottom-up Approach

11
Object Oriented Programming
Object Oriented Approach
  • Object oriented approach is fundamentally
    different from traditional process oriented
    approaches
  • It has intuitive, yet powerful constructs to
    represent
  • real-life entities and their inter-relationships
  • It is primarily based on entity abstraction in
    the
  • form of objects
  • C /JAVA is an Object Oriented language and One
    must understand the underlying concepts of this
    approach to fully utilise the Power of these
    languages
  • Object abstracts both its State and behavior,
  • rather than separate data and procedural
  • abstractions

12
OOPs Definition
  • Object Oriented Programming is a method of
    implementation in which programs are organized as
    collection of objects, each of which represent an
    instance of classes.
  • Object Oriented Programming , Grady Booch
  • Object Oriented Programming is an approach that
    provides a way of modularizing programs by
    creating partitioned memory for both data and
    functions that can be used as a template for
    creating copies on demand.
  • Object Oriented programming with C,
    Balaguruswamy

13
Object Oriented Programming
Object Oriented Modeling
  • Unified Modeling Language (UML), used for object
  • oriented modeling, provides powerful constructs
    for
  • diagrammatic representation of real-life entities
    and
  • their inter-relationships, shifting focus even
    into
  • analysis phase
  • Essentially, analysis models are only extended in
  • terms of issues like ease of implementation and
  • optimization, dynamic interactions, re-use and
  • inter-operability etc.

14
  • 1. Comments
  • 2. Load
  • 3. main
  • 3.1 Print "Welcome to C\n"
  • 3.2 exit (return 0)
  • Program Output

Welcome to C!
15
  • Load
  • 2. main
  • 2.1 Initialize variables integer1, integer2, and
    sum
  • 2.2 Print "Enter first integer"
  • 2.2.1 Get input2.3 Print "Enter second integer"
    2.3.1 Get input2.4 Add variables and put result
    into sum2.5 Print "Sum is" 2.5.1 Output sum
  • 2.6 exit (return 0)
  • Program Output

Enter first integer 45 Enter second
integer 72 Sum is 117
16
Object Oriented Programming
Abstraction
  • A mental process
  • Helps to focus attention on exclusively only
    those
  • aspects of the concerned real world phenomenon
  • relevant to the purpose
  • Differ from person-to-person and
    context-to-context
  • Eg. Library is a facility for a student
  • employer for its staff
  • investment for management

17
Object Oriented Programming
Abstraction (More Examples)
  • In real world
  • We abstract crows, sparrows, parrots etc. as
    birds
  • buses, boats, aircraft as vehicles
  • Children abstract birds and aircraft as Flying
    Things

Abstraction enable us to put "barrier" so that
"complex" details, not relevant to the purpose,
do not confuse us.
18
Object Oriented Programming
Abstraction (More Examples)
  • In programming (traditional)
  • Data abstraction (giving all essential data about
    a
  • particular entity)
  • Eg. Payslip
  • Procedural abstraction (giving various steps
    involved
  • in a procedure)
  • Eg. Print Payslip

19
Object Oriented Programming
Abstraction (More Examples)
  • In programming (object oriented)
  • We abstract objects both in terms of its behavior
  • as well as its structure
  • Eg. object "pay-slip" represents the abstraction
    of
  • details of pay, and
  • also functionalities like "compute-net-pay",
  • "compute-tax",
  • "print-pay-slip"
  • ..

20
Object Oriented Programming
Abstraction (Contd.)
  • Used to separate relevant aspects of behavior
    and
  • characteristics of a real-world entity, from the
    actual
  • implementation that enables such a behavior.
  • That is, it limits the scope of our interest to
    the behavior
  • and characteristics of the the real-world entity
    and, thus helps
  • in building up a contract or an agreement between
    the object
  • and its potential clients (who use these objects)
  • This agreement , in turn, defines the
    responsibilities of the real-
  • world entity in terms of its behavior and
    characteristics.

21
Object Oriented Programming
Encapsulation
  • Complimentary aspects of the same mental process
  • While abstraction builds up a contract that
    defines
  • the behavior, encapsulation ensures the execution
    of
  • the contract consistently
  • Eg. In the abstraction of the class of Flying
    Things,
  • encapsulation hides the fact that an aircraft is
    engine-
  • powered while the bird flies by flapping its
    wings
  • Encapsulation is achieved by hiding information
    that are not
  • required for other objects to interact with it.

22
Object Oriented Programming
Encapsulation
  • Encapsulations wrap data and its function into a
    single unit.
  • Interface defines the behavior common to all
    objects
  • of that class while implementation is the inside
    view
  • (comprising of the representation and the
    mechanism
  • that achieve the behavior) of these objects.
  • Keywords like public and private are used, as
    access
  • control constructs, to prevent a client from
    accessing
  • the implementational secrets of an object.

23
Object Oriented Programming
Objects and Classes
  • They are the basic building blocks of object
    oriented
  • technology
  • When entities are abstracted, and the abstraction
  • defines the class and specific instances
    (examples)
  • form the objects
  • Class provides the description of an abstraction
  • applying to a set of objects sharing a common
  • structure and behavior
  • Everything about an object is defined in the class

24
Object Oriented Programming
Objects
  • Objects consist of
  • visible behavior and structure as abstracted and
  • implementation details encapsulated and hidden
  • An object has
  • An identity of its own
  • State
  • Interface by which the clients are serviced
  • Implementation of its behavior

25
Object Oriented Programming
Object Identity
  • Objects thus have a unique existence
  • (in memory, from programming point of view)
  • Each object is distinguished by its name or
  • a reference (to the space in memory it occupies)
  • Objects are created at the beginning of their
    life
  • span and are destroyed at the end of it
  • Identity of an object is the means by which
    clients
  • can refer to that object.

26
Object Oriented Programming
Object State
  • represented by attributes defined as part of its
  • structure and its current values
  • When an object interacts with other objects,
  • and clients perform operations on the object,
  • Behavior of the object depends on its state
  • and
  • Also, methods invoked often alter the state

27
Object Oriented Programming
Object Behavior
  • Activity, exhibited by the object in response to
  • operations on it, that is visible outside
  • When an object interacts with other objects,
  • and clients perform operations on the object,
  • behavior of the object depends on its state

28
Object Oriented Programming
Methods
  • Operations are performed by the client by passing
  • a message to the object. The operations that can
    be
  • performed, and the format of the message (or the
  • "signature" that has to be passed), are defined
    in
  • the class as "methods
  • All the methods of a class together constitute
    the
  • interface used by the client
  • Methods are implemented as functions in the class
  • Terms operations, messages, methods, and member-
  • functions are all used interchangeably

29
Object Oriented Programming
Methods (Contd)
Two other essential operations are
  • Constructor initializing the state of an object
  • (when it is created)
  • Destructor freeing the state and destroys the
    object itself

Constructors make sure that the object is well
created, and hence can receive messages. Eg.
Say, Account object has methods such as
withdraw() and deposit(), and the current
balance as its state. Minimum deposit should be
made before opening an account, and before one
can do any transactions on that account.
30
Object Oriented Programming
Classes
  • Describes the interface and the implementation of
  • the set of objects
  • Interface of a class provides outside view (like
    a
  • contractual agreement) and declares the expected
  • behavior of objects of this class in the context
    of
  • interaction with other objects.
  • Implementation of a class is the inside view or
    the
  • Implementor's View of how the the behavior as
  • defined in the interface is accomplished.

31
  • friend function and friend classes
  • Can access private and protected members of
    another class
  • friend functions are not member functions of
    class
  • Defined outside of class scope
  • Properties of friendship
  • Friendship is granted, not taken
  • Not symmetric (if B a friend of A, A not
    necessarily a friend of B)
  • Not transitive (if A a friend of B, B a friend of
    C, A not necessarily a friend of C)

32
Friend Functions and Friend Classes
  • friend declarations
  • To declare a friend function
  • Type friend before the function prototype in the
    class that is giving friendship
  • friend int myFunction( int x )
  • should appear in the class giving friendship
  • To declare a friend class
  • Type friend class Classname in the class that is
    giving friendship
  • if ClassOne is granting friendship to ClassTwo,
    friend class ClassTwo
  • should appear in ClassOne's definition

33
  • 1. Class definition
  • 1.1 Declare function a friend
  • 1.2 Function definition
  • 1.3 Initialize Count object

34
  • 2. Modify object
  • 3. Print results
  • Program Output

counter.x after instantiation 0 counter.x after
call to setX friend function 8
Write a program to find the average of two values
using friend function
35
Operator Overloading
  • Enabling Cs operators to work with class
    objects
  • Ability to provide operators with special meaning
  • Requires great care when overloading is misused,
    program difficult to understand
  • Examples of already overloaded operators
  • Operator and the bitwise left-shift operator
  • and -, perform arithmetic on multiple types
  • Compiler generates the appropriate code based on
    the manner in which the operator is used

36
Restrictions on Operator Overloading
  • C operators that can be overloaded
  • C Operators that cannot be overloaded

37
  • Overloading an operator
  • Write function definition as normal
  • Function name is keyword operator followed by the
    symbol for the operator being overloaded
  • operator used to overload the addition operator
    ()
  • It may be either a member function or friend
    function
  • Using operators
  • To use an operator on a class object it must be
    overloaded unless the assignment operator()or
    the address operator()
  • Returntype classnameoperator op()
  • Vector operator (vector)
  • Cmplx operator(double r)

38
Restrictions on Operator Overloading
  • Overloading restrictions
  • Precedence of an operator cannot be changed
  • Associativity of an operator cannot be changed
  • Unary operators remain unary, and binary
    operators remain binary
  • Operators , , and - each have unary and
    binary versions
  • Unary and binary versions can be overloaded
    separately
  • No new operators can be created
  • Use only existing operators
  • No overloading operators for built-in types
  • Cannot change how two integers are added

39
Operator Functions as Class Members vs. as friend
Functions
  • Member vs non-member
  • Operator functions can be member or non-member
    functions
  • When overloading ( ), , - or any of the
    assignment operators, must use a member function
  • Operator functions as member functions
  • Leftmost operand must be an object (or reference
    to an object) of the class
  • If left operand of a different type, operator
    function must be a non-member function
  • Operator functions as non-member functions
  • Must be friends if needs to access private or
    protected members
  • Enable the operator to be commutative

40
include include class
complex float rp float im public complex()
complex(float r, float i) rpr imi
complex operator(complex) void
display() complex complexoperator(complex
c) complex temp temp.rp rp c.rp temp.im
im c.im return(temp)
void complexdisplay() cout rp
void main() complex c1,c2,c3 c1complex(2.
5,3.5) c2complex(1.6,2.7) c3 c1 c2
//c3 c1.operator(c2) cout
cout
ay()
41
  • It receives only one complex type argument
    explicitly
  • It returns a complex value
  • Member function can be invoked only by an object
  • Here c1 takes the responsibility of invoking the
    function and c2 plays the role of argument that
    is passed to the function.

42
(No Transcript)
43
Overloading using Friends
  • Friend function require two arguments to be
    explicitly passed.
  • In complex example
  • Replace member fn declaration as
  • Friend complex operator(complex, complex)
  • Redefine the operator fn as
  • Complex operator (complex a, complex b)
  • temp.rp a.rp b.rp
  • temp.im a.im b.im)
  • return (temp)

44
Friend istream operator(istream istr,cmplx
r) Friend ostream operatorcmplx r) Istream operator(istream istr,
cmplx r) istr r.rp istr r.im Return
istr
Ostream operatorr) Ostr
45
Useful Links in C
  • Classes
  • Classes are the standard unit of programming
  • A class is like a blueprint reusable
  • Objects are instantiated (created) from the class
  • For example, a house is an instance of a
    blueprint class
  • Introduction to Programming in C
  • http//www. c Annotations/

46
Object Oriented Programming
What is Inheritance ?
  • Feature enabling classes to be derived from other
    classes,
  • having similar behavior and structure but having
    higher
  • levels of abstraction
  • Denotes IS-A relationship and implies
    specialization
  • Subclasses inherit the interface, the attributes
    and the
  • implementation from the super-classes
  • Sub-class may need to know about methods and
    attributes
  • of super-class. This is facilitated using
    protected keyword
  • Such methods and attributes would be accessible
    to sub-
  • classes but prevent access to outside objects)

47
Object Oriented Programming
Inheritance Hierarchy
  • Captures hierarchy that exists among real life
    entities,
  • ordering abstraction to different levels
  • Hierarchical representation helps in
    comprehension
  • of abstraction of entities, making object model
    more
  • comprehensive and elegant
  • Abstracting crows, parrots, and sparrows into
    birds and
  • then describing each in terms of birds is more
    intuitive,
  • as against having each of them as separate,
    independent
  • classes with methods like fly, sing etc. defined
    for each.

48
Object Oriented Programming
Inheritance Hierarchy (Contd)
  • Higher levels of this hierarchy easily
    comprehended
  • Flying thing is identified even by a child
  • Difference between a military and a civil
    aircraft
  • understood by the general public
  • But, probably, only experts can point out
    difference
  • between a Bomber or a Fighter.
  • Defining one in terms immediately higher one
    easier
  • Explaining Vulture in terms of wildlife birds is
    easy

49
Object Oriented Programming
Inheritance Hierarchy (Example)
Flying Thing
Aircraft
Bird
Wild
Civilian
Military
Domestic
Bomber
Crow
Sparrow
Fighter
Hawk
Vulture
50
Object Oriented Programming
Inheritance (facilitating reuse in design and
programming)
Bird
eat() fly() land() takeOff()
Crow
Sparrow
caw()
chirp()
51
Object Oriented Programming
Inheritance (A finer abstraction)
Bird
eat() fly() land() takeOff() sing()
Crow
Sparrow
sing()
sing()
  • Method sing() added to classes Crow and Sparrow
  • These methods override sing() method in the
    super-class Bird.

52
Multiple Inheritance
Single Inheritance
B
A
A
B
C
53
Multilevel Inheritance
Hierarchical Inheritance
A
A
B
B
C
D
C
54
Hybrid Inheritance
A
B
C
D
55
Defining Derived Classes
Class derived class name visibility mode base
class name -------- ----------
Class ABC private XYZ // private
Derivation Class ABC public XYZ Class ABC
protected XYZ
56
Public Private visibility
  • Base class Derived Class
  • Private
  • Public Public Private

Public Private Not inherited Not.
In
57
Protected visibility
  • A member declared as protected is accessible by
    the member functions within its class and any
    class immediately derived from it.
  • When a protected member is inherited in public
    mode, it becomes protected in derived class. It
    is ready for further inheritance
  • A Protected member, inherited in private mode, it
    becomes private in the derived class. But not
    further inherited.

58
public, private, and protected Inheritance
59
include class B int
a public int b void get_ab() int
get_a() void show_a() class D public
B int c public void mul() void display()

void Bget_ab() a5 b10 int
Bget_a() return a void Bshow_a()
cout void D display() cout l cout
60
void main() D d d.get_ab() d.
mul() d.show_a() d.display() d.b
20 d.mul() d.display()
Output a5 a5 b10 c50 a5 b20 c100
61
Multiple Inheritance
  • A class can inherit the attributes of two or more
    classes.
  • Multiple Inheritance

A
C
B
Class D public A, public B ------
D
62
Hybrid Inheritance
  • There could be situations where we need to apply
    two or more types of inheritance to design a
    program. For example

Student
Example
test
Sports
Multilevel Multiple
Result
63
VIRTUAL BASE CLASSES
There are situations where we would require the
use of both the multiple and multilevel, and
hierarchical inheritance.
A
B
C
D
64
All the public and protected members of A is
inherited to D twice, this cause duplication.
The duplication of inherited members due to
these multiple paths can be avoided by making
the common base class called virtual base class
Class B1 virtual public A Class B2 public
virtual A
65
Object Oriented Programming
What is Polymorphism ?
  • Feature enabling objects of different classes to
    behave
  • differently to the same message
  • One name, multiple form
  • Also known as Late binding, runtime linking
  • Message to an object of an inherited class result
    in
  • invoking corresponding method of its super-class
  • However, super-class methods may be over-ridden
    in
  • its sub-classes
  • Design and implement systems that are more easily
    extensible

66
Object Oriented Programming
Polymorphism (Implementation)
  • Mechanism, dynamically binding the correct
  • implementation of the method to the reference, is
  • used to effect polymorphism
  • In interpreted languages like Java, the
    interpreter keeps
  • track of the class of an object referred, while
    in case of
  • compiled languages like C, the compiler
    typically
  • uses 'virtual function tables.

67
Object Oriented Programming
Advantages of Inheritance
  • Captures similarity and differences in the real
    world
  • entities and their inter-relationships
  • Facilitates re-use
  • New specialised classes can be created from Class
  • libraries, adding new functionalities as desired

68
Object Oriented Programming
Dis-advantages of Inheritance
  • Violates the principle of encapsulation
  • Inheritance may also lead to unmanageable no. of
  • class hierarchies.
  • Misusing may affect re-use as inheritance
    relations
  • between classes are bound during compilation and
  • hence the code using inheritance cannot overcome
  • dependencies showing up during runtime)

69
Object Pointers and this
  • C also uses pointers to point to an object
    created by a class.
  • ex. Item it_ptr
  • This Pointer Points to an object for which this
    function is called.
  • ex. A function call A.max() will set the pointer
    this to the address of the object A.

70
Pointers to Derived Class
  • A single pointer can be used in base as well as
    derived class.
  • If B is a base class and D is a derived class,
    then a pointer to B can also be pointer to D.
  • B ptr
  • B b D d
  • ptr b //ptr points to object b
  • ptr d //ptr points to object d

71
  • Ptr can use to access the members of B and the
    members of D that are inherited from B
  • But not the members that originally belong to D.
  • Example

72
virtual Functions
  • virtual functions
  • Suppose a set of shape classes such as Circle,
    Triangle, etc.
  • Every shape has own unique draw function but
    possible to call them by calling the draw
    function of base class Shape
  • Compiler determines dynamically (i.e., at run
    time) which to call
  • In base-class declare draw to be virtual
  • Override draw in each of the derived classes

73
Virtual Functions
  • In previous example, the compiler ignore the
    contents of the pointer, and chooses the member
    function that matched the type of the pointer.
  • When you use same function name in both base and
    derived classes, the function in base is declared
    as virtual.
  • When a function is made virtual, C determines
    which function to use at runtime based on the
    type of the object pointed to, rather than the
    type of the pointer.

74
  • virtual declaration
  • Keyword virtual before function prototype in
    base-class
  • virtual void show()
  • A base-class pointer to a derived class object
    will call the correct show function
  • bptr- show()
  • If a derived class does not define a virtual
    function, the function is inherited from the base
    class

75
Rules for Virtual Functions
  • Virtual functions must be members of class
  • They cannot be static members
  • They are accessed by using object pointers
  • It can be a friend function also
  • We cannot have virtual constructors, but can have
    virtual destructors

76
Pure Virtual Functions
  • A do-nothing function that can be defined in
    base class for implementing in derived classes.
  • Virtual void show()0
  • Such functions are called pure virtual functions.
  • Example Find out the volume and area of circle,
    cylinder by using virtual functions.

77
Object Oriented Programming
Abstract Methods Classes
  • Method specified in a class without
    implementation
  • is called abstract method
  • (Eg. Method sing can be specified in Bird
    class but
  • implemented on a sub-class)
  • Class having abstract methods is called an
    abstract
  • class
  • Instances of an abstract class cannot be created
  • (as complete behavior of the class is undefined
    and
  • would not be able to fulfil the contract without
    help
  • from its sub-classes)

78
Object Oriented Programming
Abstract Classes
  • One of the important concepts in object-oriented
  • programming and design
  • Provides a higher form of generalization
  • An abstract class can have attributes and other
  • non-abstract methods
  • Class Bird could have an attribute 'sex and also
  • behaviors eat(), fly() etc, of which eat may be
    fully
  • implemented the class itself.
Write a Comment
User Comments (0)
About PowerShow.com