Object Oriented Programming
 Programmer thinks about and defines the
attributes and behavior of objects.
 Often the objects are modeled after real-
world entities.
 Very different approach than function-based
programming (like C).
Object Oriented Programming
 Object-oriented programming (OOP)
– Encapsulates data (attributes) and functions
(behavior) into packages called classes.
 So, Classes are user-defined (programmer-
defined) types.
– Data (data members)
– Functions (member functions or methods)
 In other words, they are structures +
functions
Classes in C++
 Member access specifiers
– public:
 can be accessed outside the class directly.
– The public stuff is the interface.
– private:
 Accessible only to member functions of class
 Private members and methods are for internal use
only.
class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r)
{
radius = r;
}
double Circle::getArea()
{
return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}
void main()
{
Circle c(7);
Circle *cp1 = &c;
Circle *cp2 = new Circle(7);
cout<<“The are of cp2:”
<<cp2->getArea();
}
Another class Example
 This class shows how to handle time parts.
class Time
{
private:
int *hour,*minute,*second;
public:
Time();
Time(int h,int m,int s);
void printTime();
void setTime(int h,int m,int s);
int getHour(){return *hour;}
int getMinute(){return *minute;}
int getSecond(){return *second;}
void setHour(int h){*hour = h;}
void setMinute(int m){*minute = m;}
void setSecond(int s){*second = s;}
~Time();
};
Destructor
Time::Time()
{
hour = new int;
minute = new int;
second = new int;
*hour = *minute = *second = 0;
}
Time::Time(int h,int m,int s)
{
hour = new int;
minute = new int;
second = new int;
*hour = h;
*minute = m;
*second = s;
}
void Time::setTime(int h,int m,int s)
{
*hour = h;
*minute = m;
*second = s;
}
Dynamic locations
should be allocated
to pointers first
void Time::printTime()
{
cout<<"The time is : ("<<*hour<<":"<<*minute<<":"<<*second<<")"
<<endl;
}
Time::~Time()
{
delete hour; delete minute;delete second;
}
void main()
{
Time *t;
t= new Time(3,55,54);
t->printTime();
t->setHour(7);
t->setMinute(17);
t->setSecond(43);
t->printTime();
delete t;
}
Output:
The time is : (3:55:54)
The time is : (7:17:43)
Press any key to continue
Destructor: used here to de-
allocate memory locations
When executed, the
destructor is called
Reasons for OOP
1. Simplify programming
2. Interfaces
 Information hiding:
– Implementation details hidden within classes themselves
3. Software reuse
 Class objects included as members of other
classes

First introduced scope rules for data hiding.

Public part consists of variables and
functions that are visible outside of the
module.

Private part consists of variables and
functions visible only within the module.

Modules may span multiple compilation
units (files).

Modules generally lack any inheritance
mechanism.
Modules
Why OO-Programming?

Reduces conceptual load by reducing
amount of detail

Provides fault containment
–
Can’t use components (e.g., a class) in
inappropriate ways

Provides independence between
components
–
Design/development can be done by more than
one person

Global Variables -lifetime spans program
execution.

Local Variables - lifetime limited to execution
of a single routine.

Nested Scopes - allow functions to be local.

Static Variables - visible in single scope.

Modules - allow several subroutines to share
a set of static variables.

Module Types - multiple instances of an
abstraction.

Classes - families of related abstractions.
The Evolution of OOPS

An instance of a class is know as an
Object.

Languages that are based on classes are
know as Object-Oriented.
–
Eiffel
–
C++
–
Modula-3
–
Ada 95
–
Java
Keys to OO Programming

Encapsulation (data hiding)
–
Enable programmer to group data & subroutines
(methods) together, hiding irrelevant details from users

Inheritance
–
Enable a new abstraction (i.e., derived class) to be
defined as an extension of an existing abstraction,
retaining key characteristics

Dynamic method binding
–
Enable use of new abstraction (i.e., derived class) to
exhibit new behavior in context of old abstraction
Keys to OO Programming
Classes in C++
 A class definition begins with the keyword
class.
 The body of the class is contained within a
set of braces, { } ; (notice the semi-colon).
class class_name
{
….
….
….
};
Class body (data member
+ methods)
Any valid
identifier
Classes in C++
 Within the body, the keywords private: and
public: specify the access level of the
members of the class.
– the default is private.
 Usually, the data members of a class are
declared in the private: section of the class
and the member functions are in public:
section.
Classes in C++
class class_name
{
private:
…
…
…
public:
…
…
…
};
Public members or methods
private members or
methods
Class Example
 This class example shows how we can
encapsulate (gather) a circle information into
one package (unit or class)
class Circle
{
private:
double radius;
public:
void setRadius(double r);
double getDiameter();
double getArea();
double getCircumference();
};
No need for others classes to
access and retrieve its value
directly. The
class methods are responsible for
that only.
They are accessible from outside
the class, and they can access the
member (radius)
Creating an object of a Class
 Declaring a variable of a class type creates an
object. You can have many variables of the same
type (class).
– Instantiation
 Once an object of a certain class is instantiated, a
new memory location is created for it to store its
data members and code
 You can instantiate many objects from a class
type.
– Ex) Circle c; Circle *c;
Special Member Functions
 Constructor:
– Public function member
– called when a new object is created
(instantiated).
– Initialize data members.
– Same name as class
– No return type
– Several constructors
 Function overloading
Special Member Functions
class Circle
{
private:
double radius;
public:
Circle();
Circle(int r);
void setRadius(double r);
double getDiameter();
double getArea();
double getCircumference();
};
Constructor with no
argument
Constructor with one
argument
Implementing class methods
 Class implementation: writing the code of class
methods.
 There are two ways:
1. Member functions defined outside class
 Using Binary scope resolution operator (::)
 “Ties” member name to class name
 Uniquely identify functions of particular class
 Different classes can have member functions with same name
– Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){
…
}
Implementing class methods
2. Member functions defined inside class
– Do not need scope resolution operator, class
name;
class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Defined
inside
class
class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r)
{
radius = r;
}
double Circle::getArea()
{
return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}
Defined outside class
Accessing Class Members
 Operators to access class members
– Identical to those for structs
– Dot member selection operator (.)
 Object
 Reference to object
– Arrow member selection operator (->)
 Pointers
class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r)
{
radius = r;
}
double Circle::getArea()
{
return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}
void main()
{
Circle c1,c2(7);
cout<<“The area of c1:”
<<c1.getArea()<<“n”;
//c1.raduis = 5;//syntax error
c1.setRadius(5);
cout<<“The circumference of c1:”
<< c1.getCircumference()<<“n”;
cout<<“The Diameter of c2:”
<<c2.getDiameter()<<“n”;
}
The first
constructor is
called
The second
constructor is
called
Since radius is a
private class data
member
Classes

Extends the scope rules of modules to
include inheritance.

Should private members of a base class be
visible in derived classes?

Should public members of a base class
always be public members of a derived
class.

How much control should a base class
have over its members in derived classes?
C++ Classes

Any class can limit the visibility of its
members:
–
Public members are visible anywhere the class
is in scope.
–
Private members are visible only within the
class’s methods.
–
Protected members are visible inside members
of the class and derived classes.
–
Friend classes are granted exceptions to
(some) of the rules.
C++ Classes

Derived classes can further restrict visibility of
base class members, but not increase it:
–
Private members of a base class are never visible in a
derived class.
–
Protected and public members of a public base class
are protected or public, respectively, in a derived class.
–
Protected and public members of a protected base
class are protected members of a derived class.
–
Protected and public members of a private base class
are private members of a derived class.
C++ Classes

Derived classes that limit visibility of base class
members can restore visibility by inserting a
using declaration in its protected or public
sections.

Rules in other languages can be significantly
different.
Dynamic Method Binding
Member Lookup
Inheritance
Encapsulation

Encapsulation Requires that functions,
modules and classes:
–
Have clearly defined external interfaces
–
Hide implementation details
private data
private
functions
public functions
Abstract Data Types

Modularity
–
Keeps the complexity of a large program
manageable by systematically controlling
the interaction of its components
–
Isolates errors
Abstract Data Types

Modularity (Continued)
–
Eliminates redundancies
–
A modular program is

Easier to write

Easier to read

Easier to modify
Abstract Data Types

Procedural abstraction
–
Separates the purpose and use of a module
from its implementation
–
A module’s specifications should

Detail how the module behaves

Identify details that can be hidden within the module
Abstract Data Types

Information hiding
–
Hides certain implementation details within a
module
–
Makes these details inaccessible from outside
the module
Abstract Data Types
Figure 3.1
Isolated tasks: the implementation of task T does not affect task Q
Abstract Data Types

The isolation of modules is not total
–
Functions’ specifications, or contracts, govern how
they interact with each other
Figure 3.2 A slit in the wall
Abstract Data Types

Typical operations on data
–
Add data to a data collection
–
Remove data from a data collection
–
Ask questions about the data in a data
collection
Abstract Data Types

Data abstraction
–
Asks you to think what you can do to a
collection of data independently of how you do it
–
Allows you to develop each data structure in
relative isolation from the rest of the solution
–
A natural extension of procedural abstraction
Abstract Data Types

Abstract data type (ADT)
–
An ADT is composed of

A collection of data

A set of operations on that data
–
Specifications of an ADT indicate

What the ADT operations do, not how to implement
them
–
Implementation of an ADT

Includes choosing a particular data structure
Abstract Data Types
Figure 3.4
A wall of ADT operations isolates a data structure from the program that uses it
The ADT List

Except for the first and last items, each item
has a unique predecessor and a unique
successor

Head or front do not have a predecessor

Tail or end do not have a successor
The ADT List

Items are referenced by their position within
the list

Specifications of the ADT operations
–
Define the contract for the ADT list
–
Do not specify how to store the list or how to
perform the operations

ADT operations can be used in an
application without the knowledge of how
the operations will be implemented
The ADT List

ADT List operations
–
Create an empty list
–
Determine whether a list is empty
–
Determine the number of items in a list
–
Add an item at a given position in the list
–
Remove the item at a given position in the list
–
Remove all the items from the list
–
Retrieve (get) item at a given position in the list
The ADT List

The ADT sorted list
–
Maintains items in sorted order
–
Inserts and deletes items by their values, not
their positions
The ADT List
Figure 3.7
The wall between displayList and the implementation of the ADT list
Designing an ADT

The design of an ADT should evolve
naturally during the problem-solving process

Questions to ask when designing an ADT
–
What data does a problem require?
–
What operations does a problem require?
Designing an ADT

For complex abstract data types, the
behavior of the operations must be specified
using axioms
–
Axiom: A mathematical rule
–
Ex. : (aList.createList()).size() = 0
Implementing ADTs

Choosing the data structure to represent the
ADT’s data is a part of implementation
–
Choice of a data structure depends on

Details of the ADT’s operations

Context in which the operations will be used
Implementing ADTs

Implementation details should be hidden
behind a wall of ADT operations
–
A program would only be able to access the
data structure using the ADT operations
Implementing ADTs
Figure 3.8
ADT operations provide access to a data structure
Implementing ADTs
Figure 3.9 Violating the wall of ADT operations
C++ Classes

Encapsulation combines an ADT’s data with
its operations to form an object
–
An object is an instance of a class
–
A class contains data members and member
functions

By default, all members in a class are
private
class Rectangle{
private:
int numVertices;
float *xCoord, *yCoord;
public:
void set(float *x, float *y, int
nV);
float area();
};
Inheritance Concept
Rectangle
Triangle
Polygon
class Polygon{
private:
int numVertices;
float *xCoord, *yCoord;
public:
void set(float *x, float *y, int
nV);
};
class Triangle{
private:
int numVertices;
float *xCoord, *yCoord;
public:
void set(float *x, float *y, int
nV);
float area();
Rectangle
Triangle
Polygon
class Polygon{
protected:
int numVertices;
float *xCoord, float *yCoord;
public:
void set(float *x, float *y, int nV);
};
class Rectangle : public
Polygon{
public:
float area();
};
class Rectangle{
protected:
int numVertices;
float *xCoord, float *yCoord;
public:
void set(float *x, float *y, int nV);
float area();
};
Inheritance Concept
Rectangle
Triangle
Polygon
class Polygon{
protected:
int numVertices;
float *xCoord, float *yCoord;
public:
void set(float *x, float *y, int nV);
};
class Triangle : public
Polygon{
public:
float area();
};
class Triangle{
protected:
int numVertices;
float *xCoord, float *yCoord;
public:
void set(float *x, float *y, int
nV);
float area();
Inheritance Concept
Inheritance Concept
Point
Circle 3D-Point
class Point{
protected:
int x, y;
public:
void set (int a, int b);
};
class Circle : public Point{
private:
double r;
};
class 3D-Point: public
Point{
private:
int z;
};
x
y
x
y
r
x
y
z

Augmenting the original class

Specializing the original class
Inheritance Concept
RealNumber
ComplexNumber
ImaginaryNumber
Rectangle
Triangle
Polygon Point
Circle
real
imag
real imag
3D-Point
Why Inheritance ?
Inheritance is a mechanism for

building class types from existing class
types

defining new class types to be a
–
specialization
–
augmentation
of existing types
Define a Class Hierarchy

Syntax:
class DerivedClassName : access-level
BaseClassName
where
–
access-level specifies the type of derivation

private by default, or

public

Any class can serve as a base class
–
Thus a derived class can also be a base class
Class Derivation
Point
3D-Point
class Point{
protected:
int x, y;
public:
void set (int a, int b);
};
class 3D-Point : public
Point{
private:
double z;
… …
};
class Sphere : public 3D-
Point{
private:
double r;
… …
};
Sphere
Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
What to inherit?

In principle, every member of a base class is
inherited by a derived class
–
just with different access permission
Access Control Over the Members

Two levels of access control
over class members
–
class definition
–
inheritance type
base class/ superclass/
parent class
derived class/ subclass/
child class
derive
from
members
goes
to
class Point{
protected: int x, y;
public: void set(int a, int b);
};
class Circle : public Point{
… …
};

The type of inheritance defines the access level for the
members of derived class that are inherited from the
base class
Access Rights or access
specifiers of Derived Classes
private protected public
private - - -
protecte
d
private protected protected
public private protected public
Type of Inheritance
Access
Control
for
Members
Public Inheritance
public base class
(B)
public
members
protected
derived class
(A)
public
protected
inherited but
class A : public B
{
// Class A now inherits the
members of Class B
// with no change in the “access
specifier” for
}
// the inherited members
Protected Inheritance
protected base
class (B)
public members
protected
members
derived class
(A)
protected
protected
inherited but
class A : protected B
{
// Class A now inherits the
members of Class B
// with public members
“promoted” to protected
}
// but no other changes to the
inherited members
Private Inheritance
private base class
(B)
public members
protected
members
derived class
(A)
private
private
inherited but
class A : private B
{
// Class A now inherits the members of
Class B
// with public and protected members
}
// “promoted” to private
class daughter : ---------
mother{
private: double dPriv;
public: void mFoo ( );
};
Class Derivation
class mother{
protected: int mProc;
public: int mPubl;
private: int mPriv;
};
class daughter : ---------
mother{
private: double dPriv;
public: void dFoo ( );
};
void daughter :: dFoo ( ){
mPriv = 10; //error
mProc = 20;
};
private/protected/public
int main() {
/*….*/
}
class grandDaughter : public daughter
{
private: double gPriv;
public: void gFoo ( );
};
What to inherit?

In principle, every member of a base
class is inherited by a derived class
–
just with different access permission

However, there are exceptions for
–
constructor and destructor
–
operator=() member
–
friends
Since all these functions are class-
specific
Inheritance (continued)
class Shape
{
public:
int GetColor ( ) ;
// so derived classes can access it
protected:
int color;
};
class Two_D : public Shape
{
// put members specific to 2D shapes here
};
class Three_D : public Shape
{
// put members specific to 3D shapes here
};
Inheritance (continued)
class Square : public Two_D
{
public:
float getArea ( ) ;
protected:
float edge_length;
} ;
class Cube : public Three_D
{
public:
float getVolume ( ) ;
protected:
float edge_length;
Inheritance (continued)
int main ( )
{
Square mySquare;
Cube myCube;
// Square inherits
mySquare.getColor ( );
mySquare.getArea ( );
// Cube inherits getColor()
myCube.getColor ( );
myCube.getVolume ( );
}
Define its Own Members
Point
Circle
class Point{
protected:
int x, y;
public:
void set(int a, int b);
};
class Circle : public Point{
private:
double r;
public:
void set_r(double
c);
x
y
x
y
r
class Circle{
protected:
int x, y;
private:
double r;
public:
void set(int a, int b);
void set_r(double c);
};
The derived class can also define
its own members, in addition to
the members inherited from the
base class
Even more …

A derived class can override methods defined in its
parent class. With overriding,
–
the method in the subclass has the identical signature to the
method in the base class.
–
a subclass implements its own version of a base class
method.
class A {
protected:
int x, y;
public:
void print ()
{cout<<“From A”<<endl;}
};
class B : public A {
public:
void print ()
{cout<<“From B”<<endl;}
};
class Point{
protected:
int x, y;
public:
void set(int a, int b)
{x=a; y=b;}
void foo ();
void print();
};
class Circle : public Point{
private: double r;
public:
void set (int a, int b, double c) {
Point :: set(a, b); //same name
function call
r = c;
}
void print(); };
Access a Method
Circle C;
C.set(10,10,100); // from class
Circle
C.foo (); // from base class Point
C.print(); // from class Circle
Point A;
A.set(30,50); // from base class
Point
A.print(); // from base class Point
Putting Them Together

Time is the base class

ExtTime is the derived class
with public inheritance

The derived class can
–
inherit all members from the
base class, except the
constructor
–
access all public and protected
members of the base class
–
define its private data member
–
provide its own constructor
–
define its public member
functions
–
override functions inherited from
the base class
ExtTime
Time
Take Home Message

Inheritance is a mechanism for defining
new class types to be a specialization or
an augmentation of existing types.

In principle, every member of a base class
is inherited by a derived class with
different access permissions, except for
the constructors
POLYMORPHISM
Polymorphism:Definition

It is an important feature of OOPs.

It simply means one name, multiple forms.
Types of polymorphism

Primitively divided into two types
polymorphism
Run-time
polymorphism
Compile-time
polymorphism
Operator overloading
Function Overloading Virtual functions
Compile time polymorphism

Binding of Function call and function
definition is done during compile time. This
is known as static binding.

In function overloading and operator
overloading static binding happens, hence
they come under compile time
polymorphism.
Run-time polymorphism

Binding of Function call and function
definition is done during Run time. This is
known as late or dynamic binding.

If late binding happens in polymorphism it is
known as run-time polymorphism

C++ supports a mechanism known as
virtual functions to achieve run-time
polymorphism.
Example:
Class person
{
char name[30];
float age;
public:
person(char *s,float a)
{
strcpy(name,s);
age=a;
}
person& greater(person &x)
{
if(x.age>=age)
return x;
else
return *this;
}
void display (void)
{
cout<<name<<age;
}
};
Abstract Classes

An abstract class represents an abstract concept in C++ (such
as Shape class)
1. Defines the interfaces that all of
the concrete classes (subclasses)
share
2. Does not define state and
implementation unless it is
common to all concrete classes
3. Cannot be instantiated
Shape
Circle Polygon
Rectangle
int main()
{
Person P1(“john”,32);
Person P2(“ahmed”,38);
Person P3(“karthik”,30);
Person p=P1.greater(P2);
cout <<“elder person”;
p.display();
p=P3.greater(P2);
cout<<“younger person”;
p.display();
}
Abstract Classes

An abstract class represents an abstract concept in C++ (such
as Shape class)
1. Defines the interfaces that all of
the concrete classes (subclasses)
share
2. Does not define state and
implementation unless it is
common to all concrete classes
3. Cannot be instantiated
Shape
Circle Polygon
Rectangle
Function Overloading

C++ supports writing more than one function
with the same name but different argument
lists. This could include:
–
different data types
–
different number of arguments

The advantage is that the same apparent
function can be called to perform similar but
different tasks. The following will show an
example of this.
Function Overloading
void swap (int *a, int *b) ;
void swap (float *c, float *d) ;
void swap (char *p, char *q) ;
int main ( )
{
int a = 4, b = 6 ;
float c = 16.7, d = -7.89 ;
char p = 'M' , q = 'n' ;
swap (&a, &b) ;
swap (&c, &d) ;
Function Overloading
void swap (int *a, int *b)
{ int temp; temp = *a; *a = *b; *b = temp; }
void swap (float *c, float *d)
{ float temp; temp = *c; *c = *d; *d = temp; }
void swap (char *p, char *q)
{ char temp; temp = *p; *p = *q; *q = temp; }
Friend functions, operator
overloading
– Friend functions, operator overloading
It’s good to have friends

A friend function of a class is defined outside the
class’s scope (I.e. not member functions), yet has
the right to access the non-public members of the
class.

Single functions or entire classes may be declared
as friends of a class.

These are commonly used in operator
overloading. Perhaps the most common use of
friend functions is overloading << and >> for I/O.
Friends

Basically, when you declare something as a friend,
you give it access to your private data members.

This is useful for a lot of things – for very
interrelated classes, it more efficient (faster) than
using tons of get/set member function calls, and
they increase encapsulation by allowing more
freedom is design options.
Friends

A class doesn't control the scope of friend
functions so friend function declarations are
usually written at the beginning of a .h file. Public
and private don't apply to them.
Friends (a few gory details)

Friendship is not inherited, transitive, or reciprocal.
–
Derived classes don’t receive the privileges of friendship (more on
this when we get to inheritance in a few classes)
–
The privileges of friendship aren’t transitive. If class A declares
class B as a friend, and class B declares class C as a friend, class
C doesn’t necessarily have any special access rights to class A.
–
If class A declares class B as a friend (so class B can see class A’s
private members), class A is not automatically a friend of class B
(so class A cannot necessarily see the private data members of
class B).
Friends

class someClass {
friend void setX( someClass&, int);
int someNumber;
… rest of class definition }
// a function called setX defined in a program
void setX( someClass &c, int val) {
c.someNumber = val; }
// inside a main function
someClass myClass;
setX (myClass, 5);
//this will work, since we declared
// setX as a friend
ass Declarations
n be declared within the scope of another clas
ass." Nested classes are considered to be with
class and are available for use within that scop
a scope other than its immediate enclosing sc
name

value class Outside { value class Inside { }; }; In the same way, you can
nest as many classes as you wish in another class and you can nest as
many classes inside of other nested classes if you judge it necessary.
Just as you would manage any other class so can you exercise control
on a nested class. For example, you can declare all necessary
variables or methods in the nested class or in the nesting class. When
you create one class inside of another, there is no special
programmatic relationship between both classes: just because a class
is nested doesn't mean that the nested class has immediate access to
the members of the nesting class. They are two different classes and
they can be used separately.

The name of a nested class is not "visible" outside of the nesting class.
To access a nested class outside of the nesting class, you must qualify
the name of the nested class anywhere you want to use it. This is done
using the :: operator. For example, if you want to declare an Inside
variable somewhere in the program but outside of Outside, you must
qualify its name. Here is an example:

using namespace System;

value class COutside

{

public: void ShowOutside()

{

Console::WriteLine(L"=-= Outside =-=");

}

value class CInside

{

public: void ShowInside()

{ Console::WriteLine(L"-=- Inside -=-");

} }; };

UNIT I (1).ppt

  • 1.
    Object Oriented Programming Programmer thinks about and defines the attributes and behavior of objects.  Often the objects are modeled after real- world entities.  Very different approach than function-based programming (like C).
  • 2.
    Object Oriented Programming Object-oriented programming (OOP) – Encapsulates data (attributes) and functions (behavior) into packages called classes.  So, Classes are user-defined (programmer- defined) types. – Data (data members) – Functions (member functions or methods)  In other words, they are structures + functions
  • 3.
    Classes in C++ Member access specifiers – public:  can be accessed outside the class directly. – The public stuff is the interface. – private:  Accessible only to member functions of class  Private members and methods are for internal use only.
  • 4.
    class Circle { private: double radius; public: Circle(){ radius = 0.0;} Circle(int r); void setRadius(double r){radius = r;} double getDiameter(){ return radius *2;} double getArea(); double getCircumference(); }; Circle::Circle(int r) { radius = r; } double Circle::getArea() { return radius * radius * (22.0/7); } double Circle:: getCircumference() { return 2 * radius * (22.0/7); } void main() { Circle c(7); Circle *cp1 = &c; Circle *cp2 = new Circle(7); cout<<“The are of cp2:” <<cp2->getArea(); }
  • 5.
    Another class Example This class shows how to handle time parts. class Time { private: int *hour,*minute,*second; public: Time(); Time(int h,int m,int s); void printTime(); void setTime(int h,int m,int s); int getHour(){return *hour;} int getMinute(){return *minute;} int getSecond(){return *second;} void setHour(int h){*hour = h;} void setMinute(int m){*minute = m;} void setSecond(int s){*second = s;} ~Time(); }; Destructor
  • 6.
    Time::Time() { hour = newint; minute = new int; second = new int; *hour = *minute = *second = 0; } Time::Time(int h,int m,int s) { hour = new int; minute = new int; second = new int; *hour = h; *minute = m; *second = s; } void Time::setTime(int h,int m,int s) { *hour = h; *minute = m; *second = s; } Dynamic locations should be allocated to pointers first
  • 7.
    void Time::printTime() { cout<<"The timeis : ("<<*hour<<":"<<*minute<<":"<<*second<<")" <<endl; } Time::~Time() { delete hour; delete minute;delete second; } void main() { Time *t; t= new Time(3,55,54); t->printTime(); t->setHour(7); t->setMinute(17); t->setSecond(43); t->printTime(); delete t; } Output: The time is : (3:55:54) The time is : (7:17:43) Press any key to continue Destructor: used here to de- allocate memory locations When executed, the destructor is called
  • 8.
    Reasons for OOP 1.Simplify programming 2. Interfaces  Information hiding: – Implementation details hidden within classes themselves 3. Software reuse  Class objects included as members of other classes
  • 9.
     First introduced scoperules for data hiding.  Public part consists of variables and functions that are visible outside of the module.  Private part consists of variables and functions visible only within the module.  Modules may span multiple compilation units (files).  Modules generally lack any inheritance mechanism. Modules
  • 10.
    Why OO-Programming?  Reduces conceptualload by reducing amount of detail  Provides fault containment – Can’t use components (e.g., a class) in inappropriate ways  Provides independence between components – Design/development can be done by more than one person
  • 11.
     Global Variables -lifetimespans program execution.  Local Variables - lifetime limited to execution of a single routine.  Nested Scopes - allow functions to be local.  Static Variables - visible in single scope.  Modules - allow several subroutines to share a set of static variables.  Module Types - multiple instances of an abstraction.  Classes - families of related abstractions. The Evolution of OOPS
  • 12.
     An instance ofa class is know as an Object.  Languages that are based on classes are know as Object-Oriented. – Eiffel – C++ – Modula-3 – Ada 95 – Java Keys to OO Programming
  • 13.
     Encapsulation (data hiding) – Enableprogrammer to group data & subroutines (methods) together, hiding irrelevant details from users  Inheritance – Enable a new abstraction (i.e., derived class) to be defined as an extension of an existing abstraction, retaining key characteristics  Dynamic method binding – Enable use of new abstraction (i.e., derived class) to exhibit new behavior in context of old abstraction Keys to OO Programming
  • 14.
    Classes in C++ A class definition begins with the keyword class.  The body of the class is contained within a set of braces, { } ; (notice the semi-colon). class class_name { …. …. …. }; Class body (data member + methods) Any valid identifier
  • 15.
    Classes in C++ Within the body, the keywords private: and public: specify the access level of the members of the class. – the default is private.  Usually, the data members of a class are declared in the private: section of the class and the member functions are in public: section.
  • 16.
    Classes in C++ classclass_name { private: … … … public: … … … }; Public members or methods private members or methods
  • 17.
    Class Example  Thisclass example shows how we can encapsulate (gather) a circle information into one package (unit or class) class Circle { private: double radius; public: void setRadius(double r); double getDiameter(); double getArea(); double getCircumference(); }; No need for others classes to access and retrieve its value directly. The class methods are responsible for that only. They are accessible from outside the class, and they can access the member (radius)
  • 18.
    Creating an objectof a Class  Declaring a variable of a class type creates an object. You can have many variables of the same type (class). – Instantiation  Once an object of a certain class is instantiated, a new memory location is created for it to store its data members and code  You can instantiate many objects from a class type. – Ex) Circle c; Circle *c;
  • 19.
    Special Member Functions Constructor: – Public function member – called when a new object is created (instantiated). – Initialize data members. – Same name as class – No return type – Several constructors  Function overloading
  • 20.
    Special Member Functions classCircle { private: double radius; public: Circle(); Circle(int r); void setRadius(double r); double getDiameter(); double getArea(); double getCircumference(); }; Constructor with no argument Constructor with one argument
  • 21.
    Implementing class methods Class implementation: writing the code of class methods.  There are two ways: 1. Member functions defined outside class  Using Binary scope resolution operator (::)  “Ties” member name to class name  Uniquely identify functions of particular class  Different classes can have member functions with same name – Format for defining member functions ReturnType ClassName::MemberFunctionName( ){ … }
  • 22.
    Implementing class methods 2.Member functions defined inside class – Do not need scope resolution operator, class name; class Circle { private: double radius; public: Circle() { radius = 0.0;} Circle(int r); void setRadius(double r){radius = r;} double getDiameter(){ return radius *2;} double getArea(); double getCircumference(); }; Defined inside class
  • 23.
    class Circle { private: double radius; public: Circle(){ radius = 0.0;} Circle(int r); void setRadius(double r){radius = r;} double getDiameter(){ return radius *2;} double getArea(); double getCircumference(); }; Circle::Circle(int r) { radius = r; } double Circle::getArea() { return radius * radius * (22.0/7); } double Circle:: getCircumference() { return 2 * radius * (22.0/7); } Defined outside class
  • 24.
    Accessing Class Members Operators to access class members – Identical to those for structs – Dot member selection operator (.)  Object  Reference to object – Arrow member selection operator (->)  Pointers
  • 25.
    class Circle { private: double radius; public: Circle(){ radius = 0.0;} Circle(int r); void setRadius(double r){radius = r;} double getDiameter(){ return radius *2;} double getArea(); double getCircumference(); }; Circle::Circle(int r) { radius = r; } double Circle::getArea() { return radius * radius * (22.0/7); } double Circle:: getCircumference() { return 2 * radius * (22.0/7); } void main() { Circle c1,c2(7); cout<<“The area of c1:” <<c1.getArea()<<“n”; //c1.raduis = 5;//syntax error c1.setRadius(5); cout<<“The circumference of c1:” << c1.getCircumference()<<“n”; cout<<“The Diameter of c2:” <<c2.getDiameter()<<“n”; } The first constructor is called The second constructor is called Since radius is a private class data member
  • 26.
    Classes  Extends the scoperules of modules to include inheritance.  Should private members of a base class be visible in derived classes?  Should public members of a base class always be public members of a derived class.  How much control should a base class have over its members in derived classes?
  • 27.
    C++ Classes  Any classcan limit the visibility of its members: – Public members are visible anywhere the class is in scope. – Private members are visible only within the class’s methods. – Protected members are visible inside members of the class and derived classes. – Friend classes are granted exceptions to (some) of the rules.
  • 28.
    C++ Classes  Derived classescan further restrict visibility of base class members, but not increase it: – Private members of a base class are never visible in a derived class. – Protected and public members of a public base class are protected or public, respectively, in a derived class. – Protected and public members of a protected base class are protected members of a derived class. – Protected and public members of a private base class are private members of a derived class.
  • 29.
    C++ Classes  Derived classesthat limit visibility of base class members can restore visibility by inserting a using declaration in its protected or public sections.  Rules in other languages can be significantly different.
  • 30.
  • 31.
  • 32.
  • 33.
    Encapsulation  Encapsulation Requires thatfunctions, modules and classes: – Have clearly defined external interfaces – Hide implementation details private data private functions public functions
  • 34.
    Abstract Data Types  Modularity – Keepsthe complexity of a large program manageable by systematically controlling the interaction of its components – Isolates errors
  • 35.
    Abstract Data Types  Modularity(Continued) – Eliminates redundancies – A modular program is  Easier to write  Easier to read  Easier to modify
  • 36.
    Abstract Data Types  Proceduralabstraction – Separates the purpose and use of a module from its implementation – A module’s specifications should  Detail how the module behaves  Identify details that can be hidden within the module
  • 37.
    Abstract Data Types  Informationhiding – Hides certain implementation details within a module – Makes these details inaccessible from outside the module
  • 38.
    Abstract Data Types Figure3.1 Isolated tasks: the implementation of task T does not affect task Q
  • 39.
    Abstract Data Types  Theisolation of modules is not total – Functions’ specifications, or contracts, govern how they interact with each other Figure 3.2 A slit in the wall
  • 40.
    Abstract Data Types  Typicaloperations on data – Add data to a data collection – Remove data from a data collection – Ask questions about the data in a data collection
  • 41.
    Abstract Data Types  Dataabstraction – Asks you to think what you can do to a collection of data independently of how you do it – Allows you to develop each data structure in relative isolation from the rest of the solution – A natural extension of procedural abstraction
  • 42.
    Abstract Data Types  Abstractdata type (ADT) – An ADT is composed of  A collection of data  A set of operations on that data – Specifications of an ADT indicate  What the ADT operations do, not how to implement them – Implementation of an ADT  Includes choosing a particular data structure
  • 43.
    Abstract Data Types Figure3.4 A wall of ADT operations isolates a data structure from the program that uses it
  • 44.
    The ADT List  Exceptfor the first and last items, each item has a unique predecessor and a unique successor  Head or front do not have a predecessor  Tail or end do not have a successor
  • 45.
    The ADT List  Itemsare referenced by their position within the list  Specifications of the ADT operations – Define the contract for the ADT list – Do not specify how to store the list or how to perform the operations  ADT operations can be used in an application without the knowledge of how the operations will be implemented
  • 46.
    The ADT List  ADTList operations – Create an empty list – Determine whether a list is empty – Determine the number of items in a list – Add an item at a given position in the list – Remove the item at a given position in the list – Remove all the items from the list – Retrieve (get) item at a given position in the list
  • 47.
    The ADT List  TheADT sorted list – Maintains items in sorted order – Inserts and deletes items by their values, not their positions
  • 48.
    The ADT List Figure3.7 The wall between displayList and the implementation of the ADT list
  • 49.
    Designing an ADT  Thedesign of an ADT should evolve naturally during the problem-solving process  Questions to ask when designing an ADT – What data does a problem require? – What operations does a problem require?
  • 50.
    Designing an ADT  Forcomplex abstract data types, the behavior of the operations must be specified using axioms – Axiom: A mathematical rule – Ex. : (aList.createList()).size() = 0
  • 51.
    Implementing ADTs  Choosing thedata structure to represent the ADT’s data is a part of implementation – Choice of a data structure depends on  Details of the ADT’s operations  Context in which the operations will be used
  • 52.
    Implementing ADTs  Implementation detailsshould be hidden behind a wall of ADT operations – A program would only be able to access the data structure using the ADT operations
  • 53.
    Implementing ADTs Figure 3.8 ADToperations provide access to a data structure
  • 54.
    Implementing ADTs Figure 3.9Violating the wall of ADT operations
  • 55.
    C++ Classes  Encapsulation combinesan ADT’s data with its operations to form an object – An object is an instance of a class – A class contains data members and member functions  By default, all members in a class are private
  • 56.
    class Rectangle{ private: int numVertices; float*xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept Rectangle Triangle Polygon class Polygon{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); }; class Triangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area();
  • 57.
    Rectangle Triangle Polygon class Polygon{ protected: int numVertices; float*xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; class Rectangle : public Polygon{ public: float area(); }; class Rectangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept
  • 58.
    Rectangle Triangle Polygon class Polygon{ protected: int numVertices; float*xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; class Triangle : public Polygon{ public: float area(); }; class Triangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); Inheritance Concept
  • 59.
    Inheritance Concept Point Circle 3D-Point classPoint{ protected: int x, y; public: void set (int a, int b); }; class Circle : public Point{ private: double r; }; class 3D-Point: public Point{ private: int z; }; x y x y r x y z
  • 60.
     Augmenting the originalclass  Specializing the original class Inheritance Concept RealNumber ComplexNumber ImaginaryNumber Rectangle Triangle Polygon Point Circle real imag real imag 3D-Point
  • 61.
    Why Inheritance ? Inheritanceis a mechanism for  building class types from existing class types  defining new class types to be a – specialization – augmentation of existing types
  • 62.
    Define a ClassHierarchy  Syntax: class DerivedClassName : access-level BaseClassName where – access-level specifies the type of derivation  private by default, or  public  Any class can serve as a base class – Thus a derived class can also be a base class
  • 63.
    Class Derivation Point 3D-Point class Point{ protected: intx, y; public: void set (int a, int b); }; class 3D-Point : public Point{ private: double z; … … }; class Sphere : public 3D- Point{ private: double r; … … }; Sphere Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
  • 64.
    What to inherit?  Inprinciple, every member of a base class is inherited by a derived class – just with different access permission
  • 65.
    Access Control Overthe Members  Two levels of access control over class members – class definition – inheritance type base class/ superclass/ parent class derived class/ subclass/ child class derive from members goes to class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ … … };
  • 66.
     The type ofinheritance defines the access level for the members of derived class that are inherited from the base class Access Rights or access specifiers of Derived Classes private protected public private - - - protecte d private protected protected public private protected public Type of Inheritance Access Control for Members
  • 67.
    Public Inheritance public baseclass (B) public members protected derived class (A) public protected inherited but class A : public B { // Class A now inherits the members of Class B // with no change in the “access specifier” for } // the inherited members
  • 68.
    Protected Inheritance protected base class(B) public members protected members derived class (A) protected protected inherited but class A : protected B { // Class A now inherits the members of Class B // with public members “promoted” to protected } // but no other changes to the inherited members
  • 69.
    Private Inheritance private baseclass (B) public members protected members derived class (A) private private inherited but class A : private B { // Class A now inherits the members of Class B // with public and protected members } // “promoted” to private
  • 70.
    class daughter :--------- mother{ private: double dPriv; public: void mFoo ( ); }; Class Derivation class mother{ protected: int mProc; public: int mPubl; private: int mPriv; }; class daughter : --------- mother{ private: double dPriv; public: void dFoo ( ); }; void daughter :: dFoo ( ){ mPriv = 10; //error mProc = 20; }; private/protected/public int main() { /*….*/ } class grandDaughter : public daughter { private: double gPriv; public: void gFoo ( ); };
  • 71.
    What to inherit?  Inprinciple, every member of a base class is inherited by a derived class – just with different access permission  However, there are exceptions for – constructor and destructor – operator=() member – friends Since all these functions are class- specific
  • 72.
    Inheritance (continued) class Shape { public: intGetColor ( ) ; // so derived classes can access it protected: int color; }; class Two_D : public Shape { // put members specific to 2D shapes here }; class Three_D : public Shape { // put members specific to 3D shapes here };
  • 73.
    Inheritance (continued) class Square: public Two_D { public: float getArea ( ) ; protected: float edge_length; } ; class Cube : public Three_D { public: float getVolume ( ) ; protected: float edge_length;
  • 74.
    Inheritance (continued) int main( ) { Square mySquare; Cube myCube; // Square inherits mySquare.getColor ( ); mySquare.getArea ( ); // Cube inherits getColor() myCube.getColor ( ); myCube.getVolume ( ); }
  • 75.
    Define its OwnMembers Point Circle class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ private: double r; public: void set_r(double c); x y x y r class Circle{ protected: int x, y; private: double r; public: void set(int a, int b); void set_r(double c); }; The derived class can also define its own members, in addition to the members inherited from the base class
  • 76.
    Even more …  Aderived class can override methods defined in its parent class. With overriding, – the method in the subclass has the identical signature to the method in the base class. – a subclass implements its own version of a base class method. class A { protected: int x, y; public: void print () {cout<<“From A”<<endl;} }; class B : public A { public: void print () {cout<<“From B”<<endl;} };
  • 77.
    class Point{ protected: int x,y; public: void set(int a, int b) {x=a; y=b;} void foo (); void print(); }; class Circle : public Point{ private: double r; public: void set (int a, int b, double c) { Point :: set(a, b); //same name function call r = c; } void print(); }; Access a Method Circle C; C.set(10,10,100); // from class Circle C.foo (); // from base class Point C.print(); // from class Circle Point A; A.set(30,50); // from base class Point A.print(); // from base class Point
  • 78.
    Putting Them Together  Timeis the base class  ExtTime is the derived class with public inheritance  The derived class can – inherit all members from the base class, except the constructor – access all public and protected members of the base class – define its private data member – provide its own constructor – define its public member functions – override functions inherited from the base class ExtTime Time
  • 79.
    Take Home Message  Inheritanceis a mechanism for defining new class types to be a specialization or an augmentation of existing types.  In principle, every member of a base class is inherited by a derived class with different access permissions, except for the constructors
  • 80.
  • 81.
    Polymorphism:Definition  It is animportant feature of OOPs.  It simply means one name, multiple forms.
  • 82.
    Types of polymorphism  Primitivelydivided into two types polymorphism Run-time polymorphism Compile-time polymorphism Operator overloading Function Overloading Virtual functions
  • 83.
    Compile time polymorphism  Bindingof Function call and function definition is done during compile time. This is known as static binding.  In function overloading and operator overloading static binding happens, hence they come under compile time polymorphism.
  • 84.
    Run-time polymorphism  Binding ofFunction call and function definition is done during Run time. This is known as late or dynamic binding.  If late binding happens in polymorphism it is known as run-time polymorphism  C++ supports a mechanism known as virtual functions to achieve run-time polymorphism.
  • 85.
    Example: Class person { char name[30]; floatage; public: person(char *s,float a) { strcpy(name,s); age=a; } person& greater(person &x) { if(x.age>=age) return x; else return *this; } void display (void) { cout<<name<<age; } };
  • 86.
    Abstract Classes  An abstractclass represents an abstract concept in C++ (such as Shape class) 1. Defines the interfaces that all of the concrete classes (subclasses) share 2. Does not define state and implementation unless it is common to all concrete classes 3. Cannot be instantiated Shape Circle Polygon Rectangle
  • 87.
    int main() { Person P1(“john”,32); PersonP2(“ahmed”,38); Person P3(“karthik”,30); Person p=P1.greater(P2); cout <<“elder person”; p.display(); p=P3.greater(P2); cout<<“younger person”; p.display(); }
  • 88.
    Abstract Classes  An abstractclass represents an abstract concept in C++ (such as Shape class) 1. Defines the interfaces that all of the concrete classes (subclasses) share 2. Does not define state and implementation unless it is common to all concrete classes 3. Cannot be instantiated Shape Circle Polygon Rectangle
  • 89.
    Function Overloading  C++ supportswriting more than one function with the same name but different argument lists. This could include: – different data types – different number of arguments  The advantage is that the same apparent function can be called to perform similar but different tasks. The following will show an example of this.
  • 90.
    Function Overloading void swap(int *a, int *b) ; void swap (float *c, float *d) ; void swap (char *p, char *q) ; int main ( ) { int a = 4, b = 6 ; float c = 16.7, d = -7.89 ; char p = 'M' , q = 'n' ; swap (&a, &b) ; swap (&c, &d) ;
  • 91.
    Function Overloading void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } void swap (float *c, float *d) { float temp; temp = *c; *c = *d; *d = temp; } void swap (char *p, char *q) { char temp; temp = *p; *p = *q; *q = temp; }
  • 92.
    Friend functions, operator overloading –Friend functions, operator overloading
  • 93.
    It’s good tohave friends  A friend function of a class is defined outside the class’s scope (I.e. not member functions), yet has the right to access the non-public members of the class.  Single functions or entire classes may be declared as friends of a class.  These are commonly used in operator overloading. Perhaps the most common use of friend functions is overloading << and >> for I/O.
  • 94.
    Friends  Basically, when youdeclare something as a friend, you give it access to your private data members.  This is useful for a lot of things – for very interrelated classes, it more efficient (faster) than using tons of get/set member function calls, and they increase encapsulation by allowing more freedom is design options.
  • 95.
    Friends  A class doesn'tcontrol the scope of friend functions so friend function declarations are usually written at the beginning of a .h file. Public and private don't apply to them.
  • 96.
    Friends (a fewgory details)  Friendship is not inherited, transitive, or reciprocal. – Derived classes don’t receive the privileges of friendship (more on this when we get to inheritance in a few classes) – The privileges of friendship aren’t transitive. If class A declares class B as a friend, and class B declares class C as a friend, class C doesn’t necessarily have any special access rights to class A. – If class A declares class B as a friend (so class B can see class A’s private members), class A is not automatically a friend of class B (so class A cannot necessarily see the private data members of class B).
  • 97.
    Friends  class someClass { friendvoid setX( someClass&, int); int someNumber; … rest of class definition } // a function called setX defined in a program void setX( someClass &c, int val) { c.someNumber = val; } // inside a main function someClass myClass; setX (myClass, 5); //this will work, since we declared // setX as a friend
  • 98.
    ass Declarations n bedeclared within the scope of another clas ass." Nested classes are considered to be with class and are available for use within that scop a scope other than its immediate enclosing sc name
  • 99.
     value class Outside{ value class Inside { }; }; In the same way, you can nest as many classes as you wish in another class and you can nest as many classes inside of other nested classes if you judge it necessary. Just as you would manage any other class so can you exercise control on a nested class. For example, you can declare all necessary variables or methods in the nested class or in the nesting class. When you create one class inside of another, there is no special programmatic relationship between both classes: just because a class is nested doesn't mean that the nested class has immediate access to the members of the nesting class. They are two different classes and they can be used separately.  The name of a nested class is not "visible" outside of the nesting class. To access a nested class outside of the nesting class, you must qualify the name of the nested class anywhere you want to use it. This is done using the :: operator. For example, if you want to declare an Inside variable somewhere in the program but outside of Outside, you must qualify its name. Here is an example:
  • 100.
     using namespace System;  valueclass COutside  {  public: void ShowOutside()  {  Console::WriteLine(L"=-= Outside =-=");  }  value class CInside  {  public: void ShowInside()  { Console::WriteLine(L"-=- Inside -=-");  } }; };