You are on page 1of 41

Object Oriented Programming

PREPARED BY,
M.P.Geetha,
Department of CSE
CONTENTS
Basic Concepts and benefits of OOP – Tokens –
Keywords - Identifiers – Basic data types – Derived data types
– Reference variables – Type modifiers – Type casting –
Operators and control statements – Input and output
statements. Classes and Objects – Class specification – Member
function definition – Constructors – Parameterized
constructors – Overloaded Constructors – Constructors with
default arguments – Copy constructors – access qualifiers –
Static data members and member functions – Instance
creation – Array of objects – Introduction to friend function –
Destructors.
High-Level Languages

The syntax of High-level languages is similar to


English.
Historically, we divide HL languages into two groups:

Procedural languages
Object-Oriented languages (OOP)

3
Procedural Languages
Early high-level languages are typically called
procedural languages.
Procedural languages are characterized by sequential
sets of linear commands. The focus of such languages
is on structure.
Examples include C, COBOL, Fortran, LISP, Perl,
HTML, VBScript

4
Object-Oriented Languages
Most object-oriented languages are high-level
languages.
The focus of OOP languages is not on structure, but on
modeling data.
Programmers code using “blueprints” of data models
called classes.
Examples of OOP languages include C++, Visual
Basic.NET and Java.

5
PROCEDURAL PROGRAMMING
 Procedural programming is a classic programming
where the program language is used to tell the computer
EXACTLY what to do - step by step.
 A program in a procedural language is a list of
instruction. That is, each statement in the language tell the
computer to do something.
 The focus of procedural programming is to break
down a programming task into a collection of
variables, data structures, and subroutines.
In PPL, functions are unrestricted access to global data.
Two type of data
Local data (that is hidden inside a function)
Global data (that can be accessed by any function in the
program).
Problem-larger number of potential connections between
functions and data as shown in following Fig.

Global Data Global Data Global Data

Function Function Function Function


FEATURES PROCEDURE ORIENTED
OBJECT ORIENTED PROGRAMMING
PROGRAMMING
program is divided into small parts called
Divided Into program is divided into parts called objects.
functions.
Object-Oriented Programming vs. Procedural Programming 
In POP, Importance is not given to data but to
In OOP, Importance is given to the data
Importance functions as well as sequence of actions to be
because it works as a real world.
done.
Approach Top Down approach. Bottom Up approach.
Access
No access specifier. Public, Private, Protected, etc.
Specifiers
Data can move freely from function to Objects can move and communicate with
Data Moving
function each other through member functions.
To add new data and function in POP is not so OOP provides an easy way to add new data
Expansion
easy. and function.
In POP, Most function uses Global data for In OOP, data can not move easily from
Data Access sharing that can be accessed freely from function to function, it can be kept public or
function to function in the system. private so we can control the access of data.
It does not have any proper way for hiding OOP provides Data Hiding so provides more
Data Hiding
data so it is less secure. security.
overloading is possible in the form of
Overloading Overloading is not possible. Function Overloading and Operator
Overloading.
Examples C, VB, FORTRAN, Pascal. C++, JAVA, VB.NET, C#.NET.
Basic Concepts of OOP
 Objects: Objects are the basic run time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program has
to handle.
 Classes :The entire set of data and code of an object can be made a user-defined data type
with the help of class.
 Encapsulation : The wrapping up of data and function into a single unit (called class) is
known as encapsulation.
 Inheritance: It is the process by which objects of one class acquired the properties of
objects of another classes.
 Polymorphism: Polymorphism is another important OOP concept. Polymorphism, a Greek
term, means the ability to take more than on form.
 Dynamic Binding: Binding refers to the linking of a procedure call to the code to be
executed in response to the call.
 Message Passing: An object-oriented program consists of a set of objects that
communicate with each other.

9
CONCEPTS OF OOP
 CLASSES: A class is an object-oriented concept which is used to
describe properties and behavior of a real world entity.   
 A class is a combination of state (data) and behavior (methods).    
 In object-oriented languages, a class is a data type, and objects are
instances of that data type.  
 In other words, classes are prototypes from which objects are
created. 
 It has the data and its associated function wrapped in it.
 The variables declared inside a class are known as "Data Members"
and the functions are known as "Member Functions".

For example, a class Human, which is a collection of all humans in the world.

Humans have state, such as height, weight, and hair color. 


They also have behaviors, such as walking, talking, eating.  
All of the state and behaviors of a human is encapsulated (contained)
within the class human.
Representation of class
Class name Human

Attributes Name
Hair color
talking
Operations
walking

Circle

Radius
center
Calculate area()
Draw()
SYNTAX
class class-name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
Example:
#include <iostream.h>
class Square
{
private: void main()
int side, a; {
public:
Square x;
int area( side)
x.area(10);
{
a =side*side;
x.show();
return a; }
}
void show() Result:
{
cout << "The area is::" << a;
The area is:: 100
}
};
OBJECTS:
An object is an instance of a class. An object can
communicate with other objects using messages.  An object passes a
message to another object, which results in the invocation of a
method.  Objects then perform the actions that are required to get a
response from the system.

Data Members: A class contains data members. Data members are used
to store characteristics information of a real world entity in a class.
For example, name is the data member of the Human class.
 Fields/attributes and methods/operation are referred to as
class members.
Fields and Methods: Objects in a class have a number of shared
properties/features/attributes.  
 Fields are the variables contained in a class.
 Methods are functions that represent the operations associated
with a particular class.  
INHERITANCE:
One of the powerful features of c++ is inheritance.

• Inheritance is a way to form new classes using classes


that have already been defined.

• Inheritance increase the functionality of previously


defined classes without having to rewrite the original class
declaration.
POLYMORPHISM:
“one interface and many purpose”.
Two types:
Compiletime polymorphism
Runtime polymorphism
Structure of Object Oriented Program in c+
+
#include<iostream.h> Header File
Class class-name
{
access-specifiers…
int i,j;
float f;
Variables or fields
class

char ch;
double b;
access-specifiers…
void function-name() Class members
{
statement 1; Function or Method
statement 2;
}
}
main()
{
class-name.obj-name;
}
Object of class
EXAMPLE
#include <iostream.h>
class Cube
{ void main()
public: {
Cube x;
int cub( val)
x.cub(2);
{ x.show();
r = val*val*val; return r; }
}
void show()
Result:
{ cout << "The cube is::" << r; } The cbe is :: 8
private:
int val, r; }x;

In the above example "x" is an object of the class "Cube“


used to access the functions inside the class.
Access specifiers
• Defines the access rights for the statements or functions
that follows it until another access specifier or till the
end of a class. The three types of access specifiers are
"private", "public", "protected".
• private: The members declared as "private" can be
accessed only within the same class and not from
outside the class.
• public: The members declared as "public" are
accessible within the class as well as from outside the
class.
• protected: The members declared as "protected"
cannot be accessed from outside the class, but can be
accessed from a derived class. This is used when
inheritaance is applied to the members of a class.
The following table lists the visibility of the base
class members in the derived classes

 
Derived Class Visibility

Base Class Protected


Public derivation Private derivation
derivation
Visibility
Private Not inherited Not inherited Not inherited

Protected Protected Private Protected

Public Public Private Protected


Static data member

A static member is shared by all objects of the


class.
uses static keyword.
All static data is initialized to zero when the first
object is created, if no other initialization is
present.
 redeclaring the static variable, use the scope
resolution operator :: to identify which class it
belongs to.
class stat
{    
int code;
    static int count;

Example
   public:
    void setcode()
    {       code=++count;
    }
    void showcode()
Count Objects: 2
    {      cout<<"\n\tObject number is :"<<code;
Object Number is: 1
    }
Count Objects: 2
    static void showcount()
Object Number is: 2
    {              cout<<"\n\tCount Objects :"<<count;
    }
};
Int stat::count;
 void main()
{   stat obj1,obj2;
    obj1.showcount();
   obj1.showcode();
   obj2.showcount();
   obj2.showcode();}
Static Member function
Can access only static data members.
Static function can be called using class name
Classname::function_name(args);
Static Member function
class IDGenerator
{
private:
    static int s_nNextID;
 
The next ID is: 1
public:
The next ID is: 2
     static int GetNextID() { return
The next ID is: 3
s_nNextID++; }
The next ID is: 4
};
The next ID is: 5
 int IDGenerator::s_nNextID = 1;
 
int main()
{
    for (int i=0; i < 5; i++)
     cout << "The next ID is: "
<<IDGenerator::GetNextID()
 }
Friend function & friend Class

– friend function and friend classes


– Can access private and protected (more later) members of
another class
– friend functions are not member functions of class
– Defined outside of class scope

– Properties
– 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)
Friend function & friend Class
– friend declarations
 friend function
 Keyword friend before function prototype in class that is giving
friendship.
– friend int myFunction( int x );

– Appears in the class granting friendship

 friend class
 Type friend class Classname in class granting friendship

 If ClassOne granting friendship to ClassTwo,

friend class ClassTwo;


appears in ClassOne's definition
Example
class  base
{
     int val1,val2;
   public:
void get()
    {       cout<<"Enter two values:";
      cin>>val1>>val2;
     }
   friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
void main()
{    
    base obj;
    obj.get();
    cout<<"\n Mean value is : "<<mean(obj);
 }          
FRIEND CLASS
class TwoValues {
int a;
int b;
public:
TwoValues(int i, int j) { a = i; b = j; }
friend class Min;
};
class Min {
public:
int min(TwoValues x);
};
int Min::min(TwoValues x)
{
return x.a < x.b ? x.a : x.b;
}
int main()
{
TwoValues ob(10, 20);
Min m;
cout << m.min(ob);
}
this pointer

• This pointer points to the object that invoked the


function
• When a member function is called with an object , it is
automatically passed an implicit argument that is a
pointer to the invoking object (that is, the object on
which the function is called).
• Access member of object:
Syntax: obj.function_name();
Example: this points to o1 object

o1.read_data();
class max {
int a; THIS POINTER
public:
void getdata()
{ cout<<"Enter the Value :"; cin>>a;
}
max greater(max &x)
{
if(x.a>=a)
return x;
else
return *this; Answer:
} Enter the value:45
void display() Enter the value:12
{ Maximum No is: 45
cout<<"Maximum No. is : "<<a;
} };
main()
{
max one,two,three;
one.getdata();
two.getdata();
three=one.greater(two);
three.display();
}
Constructor and Destructor
• Constructor is a special member function that has the same
name as the class name used to create, initialize object of
that class.
• Constructor is called when an object is created
• no return type.
• It should be declared in public.
class A {
int i;
public:
A(); //Constructor declared
};
A::A() // Constructor definition { i=1; }
Types of Constructor
Five types

Default Constructor
Parameterized Constructor
Overloaded Constructor
Copy Constructor
Dynamic Constructor
Default & Parameterized Constructor
• Default constructor has no argument also called no
argument constructor.
• A parameterized Constructor is one that has
parameters specified in it .
• Arguments can be passed to constructor function
when object are created.
• A constructor that can take arguments are called
parameterized constructors
EXAMPLE
class cube {
int side;
public:
cube() // default constructor
{
side=10;
}
cube(int x) //parameterized constructor
{
side=x;
} };
int main()
{
cube c;
cube c1(20);
cout << c.side;
cout << c1.side;
}
Copy Constructor

Copy Constructor is used to declare and initialize an


object from another object.
For example the statement :
abc c2(c1) ;
Would define the object c 2 and at the same time
initialize it to the value of c1
Example for Copy constructor
class abc
{
int a;
int b;
Public:
abc(int x, int y)
{
a=x;
b=y;
}
abc(abc &p)
{
a=p.a;
b=p.b;
}
Void display()
{ cout<<“a= “<<a<<“\nb= “<<b;
}};
Void main()
{
abc o1(3,2 );
abc o2(o1); //Explicit call
abc o3=o2; //Implicit call
o1.display();
o2.display();
O3.display();
}
Overloaded Constructor

 If more than one constructor are implemented


in a program then it is called as overloaded
constructor.
Dynamic Constructor
class str void show()
{ {
char *name; cout<<"NAME IS:->"<<name;
int len; }};
public:
str() void main()
{ {
len=0;
char *first="HARSHIL";
str
name=newchar[len+1]; n1(first),n2("NINAD"),n3("PRATIK")
} ,
str(char *s) n4,n5;
{ n1.show();
len=strlen(s); n2.show();
name=newchar[len+1]; n3.show();
strcpy(name,s); n4.show();
n5.show();
}
}
Destructor
• Special member function has the same name as the
class name.
• Used to release the dynamically allocated memory.
• It should be declared in public and has no return type.
• Syntax
class name
Example for destructor
class Marks {
public:
int maths;
int science;
Marks() //constructor OUTPUT:
{ Inside Constructor
cout << "Inside Constructor"; C++ Object created
cout << "C++ Object created“; Inside Constructor
} C++ Object created
//Destructor Inside Destructor
~Marks() C++ Object destructed
{ Inside Destructor
cout << "Inside Destructor"; C++ Object destructed
cout << "C++ Object destructed";
} };
int main( )
{
Marks m1;
Marks m2;
return 0;
}
TEXT BOOKS:

1.C++: A Beginner's Guide, Second Edition, Herbert Schildt, TMH,


2010
2.C++: The Complete Reference, Herbert Schildt, 4th Edition, TMH,
2003
3.M. A. Weiss,“Data Structures and Algorithm Analysis in C”, 3rded,
Pearson Education,Asia,2009.

REFERENCES:

1. Y. Langsam, M. J. Augenstein and A. M. Tenenbaum, “Data


Structures using C”, Pearson Education Asia, 2004.

2.Richard F. Gilberg, Behrouz A. Forouzan, “Data Structures – A


Pseudocode Approach with C”, ThomsonBrooks / COLE, 1998.

3. Aho, J. E. Hopcroft and J. D. Ullman, “Data Structures and


Algorithms”, Pearson education Asia, 1983.
WEB RESOURCES

https://en.wikipedia.org/?title=Object-
oriented_programming

https://en.wikipedia.org/wiki/Data_structure

http://www.virtualians.net/page/handsout#.VYe5dVLA2-s

http://www.nptel.ac.in/courses/106104072/

You might also like