Introduction To Object Oriented Programming1
Introduction To Object Oriented Programming1
Evolution of languages
Object
Oriented
Procedure
Oriented
Assembly
Machine
Language
Introduction to Object Oriented Programming
Generic
Object Oriented
Modular
Procedure
Oriented
Unstructured
Programming
Introduction to Object Oriented Programming
Unstructured Programming
Main Program
Data
Introduction to Object Oriented Programming
• Fundamentals of OOP
Introduction to Object Oriented Programming
Procedural Programming
Procedure
Main 1
Program Data
Procedure
2
Introduction to Object Oriented Programming
Main Program
Data
Module2
Module1
Data1 Data2
Data1
Data3 Data2
Procedure1 Procedure2
Procedure1
Introduction to Object Oriented Programming
Object1 Object2
Data1 Data2
Procedure1 Procedure2
Object3
Data3
Procedure3
Introduction to Object Oriented Programming
Generic Programming
Generic Programming
Generic Programming
Generic Programming
So…
• Generic programming is programming that
focuses on the algorithms and code at a
higher level of abstraction that “normal”
programming.
• It is one way of using features such as
templates, so is in some sense an
application of templates.
Introduction to Object Oriented Programming
Generic Programming
Main Program
Data
Function1 Function3
Function2
Function5
Function4
Function6 Function8
Function7
Introduction to Object Oriented Programming
Procedural Programming
Procedural Paradigm
Global Global
Data Data
Procedural Programming
Fundamentals of OOP
Objects
Classes
Data Encapsulation
Data Abstraction
Inheritance
Polymorphism
Introduction to Object Oriented Programming
Objects
Data
Member
Function
Member
Function
Introduction to Object Oriented Programming
Objects…..Analogy
Students
Data
Office
Supritendant
Secretary
Introduction to Object Oriented Programming
Objects
Elements
Physical Human Collections
of Data
Objects Entities of data
Computers Stotrage
Constructs
Objects
Operation
Operation
Example: StudentObject
Enroll()
st_name
st_id
Performa Displayinfo()
branch
nce()
semester
Result()
Introduction to Object Oriented Programming
Class
Class
Object3
Object1 Object2
Class
Introduction to Object Oriented Programming
Encapsulation
Data + Logic
Object
Introduction to Object Oriented Programming
Encapsulation
Allows modularity
Class: student
Functions: Enroll()
Displayinfo()
Result()
Performance()
Introduction to Object Oriented Programming
Abstraction
Inheritance
Shape
Square Circle
Cube Cylinder
Introduction to Object Oriented Programming
Inheritance
Point
Line
Introduction to Object Oriented Programming
Polymorphism
+
Introduction to Object Oriented Programming
Dynamic Binding
Message Passing
StudentObject FacultyObject
MgmtObject Performance
Result
Programming with C++
• Variable Declaration
• Global Scope
• const
• Reference Variables
• Comments
• Function Prototypes
• Inline functions
Programming with C++
• Function Overloading
• Default and Constant arguments
C++ Perl
(numbers, objects) (text, numbers)
Java
(objects)
Variable Declaration
Difficult to debug
Const Qualifier
• int i = 3;
int &r = i;
A pointer can be re-assigned any number of times while a reference can not
be reassigned after initialization.
A pointer can point to NULL while reference can never point to NULL
You can't take the address of a reference like you can with pointers
There's no "reference arithmetics" (but you can take the address of an object
pointed by a reference and do pointer arithmetics on it as in &obj + 5).
A pointer needs to be dereferenced with * to access the memory location it points to,
whereas a reference can be used directly. A pointer to a class/struct uses -> to access
it's members whereas a reference uses a ‘. ’
Pointers Vs Reference Variables
• int x = 5; int x = 5;
int y = 6; int y = 6;
int *p; int &r = x;
p = &x;
p = &y;
*p = 10;
assert(x == 5);
assert(y == 10);
int *p = NULL; int &r = NULL;
compiling error
Pointers Vs Reference Variables
int x = 5; int x = 5;
int *p = &x; int &r = x;
p++; r++;
compiling error , but can
use &r+1;
1750
5308
Comments
• (old C style) /* */
– /* this is an old-style comment
– which can go across multiple
– lines of code */
C++ Overview
Include Files
Class Definition
int main() {
Starts definition of special function
main()
cout << "Hello World\n";
output (print) a
string
return 0;
} Program returns a status
code (0 means OK)
Preprocessing
Temporary file
C++ (C++ program) C++
Preprocessor Compiler
Executable
C++ Program Program
Input/Output
I/O
objects
cin,
cout
Input And Output of C++
Input And Output of C++
Input And Output of C++
Input And Output of C++
Seperating Lines of Output
#include <iostream>
int main() {
// Extract length and width
cout << "Rectangle dimensions: ";
float Length;
float Width;
cin >> Length >> Width;
RESERVED KEYWORDS
IDENTIFIERS
LITERALS
OPERATORS
SEPARATORS
Reserved Keywords
• Programmer-designed tokens
• Meaningful & short
• Long enough to understand
• C++ rules for Identifiers
- alphabets, digits, underscore
- should not start with digits.
- Case sensitive
- Unlimited length
- Declared anywhere
Literals
C++ stmts
Control
stmt
If contin
If switch while do for break
ue
return
else
Function Prototype
main() main()
{
{
}
-----
-----
function f1()
.
{
.
---
----
}
-----
function f2()
Return 0;
{
}
---
}
Function Prototype
Function Call :
• functionName (argument);
or
• functionName(argument1, argument2, …);
• Example
cout << sqrt( 900.0 );
• sqrt (square root) function
• The preceding statement would print 30
• All functions in math library return a double
Function Calling
• Calling/invoking a function
– sqrt(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result
– Parameter list
• Comma separated list of arguments
– Data type needed for each argument
• If no arguments, use void or leave blank
– Return-value-type
• Data type of result returned (use void if nothing returned)
Function Definition
• Example function
int square( int y )
{
return y * y;
}
• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
• Functions cannot be defined inside other functions
// Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies
int square( int ); // function prototype data types of arguments and
return values. square
int main()
expects an int, and returns
{
an int.
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call
Function Example
cout << endl;
When done, it returns the result.
return 0; // indicates successful termination
} // end main
1 4 9 16 25 36 49 64 81 100
Inline Functions
class CStr
{
char *pData; Inline functions within class declarations
int nLength;
…
public:
…
char *get_Data(void) //implicit inline function
{return pData; }
int getlength(void);
…
};
Example of Inline Functions
int main(void)
{
In both cases, the compiler will insert the code
char *s;
of the functions get_Data() and getlength()
int n;
instead of generating calls to these functions
CStr a(“Joe”);
s = a.get_Data();
n = b.getlength();
}
Function Overloading
• Syntax:
int f(int x, int y=0, int n) int f(int x, int y=0, int n=1)
// illegal // legal
Constant Arguments
.get ( ) ;
Example:
char ch ;
ch = cin.get ( ) ; // gets one character from keyboard
// & assigns it to the variable "ch"
.get (character) ;
Example:
char ch ;
cin.get (ch) ; // gets one character from
// keyboard & assigns to "ch"
Input Stream Functions
Example:
char name[40] ;
cin.getline (name, 40) ; // Gets up to 39 characters
// and inserts a null at the end of the
// string "name". If a delimiter is
// found, the read terminates. The
// delimiter is not stored in the array,
// but it is left in the stream.
Input Stream Functions
.read( ) ; .write( ) ;
Ex:
char gross[144] ;
– delete pointer ;
– delete [] pointer ;
– delete pointer ;
– delete [] pointer ;
• Defining A Class
• Data Members
• Access specifier
• Constructors
• Method Implementation in C++
• Accessing Class Member
• Destructors
Classes And Objects
• Class as ADTs
Classes And Objects
• Friend function
• Dynamic memory Allocation
•Array of Objects
•Pointers and Classes
•Class as ADTs
Classes And Objects
Data members
Members functions
};
Class Specification
• class Student
{
int st_id; Data Members or Properties of
char st_name[]; Student Class
};
Class Specification
• Visibility of Data members & Member functions
public - accessed by member functions and all
other non-member functions in the
program.
private - accessed by only member functions of the
class.
protected - similar to private, but accessed by
all the member functions of
immediate derived class
default - all items defined in the class are private.
Classes And Objects
class class_name
{
private:
…
…
…
public:
…
…
…
};
Classes
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; Defined outside class
}
double Circle::getArea()
{
return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}
Method Implementation
The second
constructor is
called
#include <iostream.h>
class Rectangle
{
public:
Rectangle();
~Rectangle();
void SetLength(int length)
{
this->itsLength = length;
}
int GetLength() const
{
return this->itsLength;
}
void SetWidth(int width)
{
itsWidth = width;
}
‘this ‘ pointer
int main()
{
Rectangle theRect;
cout << "theRect is " << theRect.GetLength() << " feet long.\n";
cout << "theRect is " << theRect.GetWidth() << " feet wide.\n";
theRect.SetLength(20);
theRect.SetWidth(10);
cout << "theRect is " << theRect.GetLength()<< " feet long.\n";
cout << "theRect is " << theRect.GetWidth()<< " feet wide.\n";
return 0;
}
Output:
theRect is 10 feet long. theRect is 5 feet wide. theRect is 20 feet long. theRect is
10 feet wide.
Constructors
• A constructor is a special member function
whose task is to initialize the objects of its
class.
• It is special because its name is same as the
class name.
• The constructor is invoked whenever an object
of its associated class is created.
• It is called constructor because it constructs
the values of data members of the class.
Constructor - example
class add • When a class contains a
{ constructor, it is
int m, n ; guaranteed that an object
public : created by the class will be
add (void) ; initialized automatically.
}; • add a ;
add :: add (void) • Not only creates the object
{ a of type add but also
m = 0; n = 0; initializes its data members
} m and n to zero.
Constructors
continue …
class Line
{
private:
double length;
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
};
Program
// Member functions definitions
Line::Line(void)
{
cout << "Object is being created" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line:: getLength( void )
{
return length;
}
Program
int main( )
{
Line line;
line.setLength(6.0); // set line length
cout << "Length of line : " ;
line.getLength();
return 0;
}
Program Output
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
};
Program
// Member functions definitions including constructor
Line::Line( double len)
{
cout << "Object is being created, length = " << len<<“\n”;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
Program
int main( )
{
Line line(10.0); // get initially set length.
cout << "Length of line : " ;
cout<<line.getLength() <<endl;
• Add( ) ; // No arguments
The statement
I 2 = I 1;
will not invoke the copy constructor.
• Destructors
– Special member function
– Same name as class
• Preceded with tilde (~)
– No arguments
– No return value
– Cannot be overloaded
– Before system reclaims object’s memory
• Reuse memory for new objects
• Mainly used to de-allocate dynamic memory locations
Destructor
Destructor
Example Of Destructor
void Time::printTime(){
cout<<"The time is :
"<<*hour<<":"<<*minute<<":"<<*second<<")"
<<endl;
}
Destructor: used here to de-allocate
Time::~Time() memory locations
{
delete hour; delete minute;delete second;
}
Output:
void main()
{
The time is : (3:55:54)
Time *t; The time is : (7:17:43)
t= new Time(3,55,54); Press any key to continue
t->printTime();
t->setHour(7);
t->setMinute(17);
t->setSecond(43); When executed, the destructor
t->printTime(); is called
delete t;}
Programs for Implementation
• Pgm to create a class Complex to add two
complex numbers using parmeterized
constructor.
• Pgm to create a class Complex to add two
complex numbers using copy constructor.
• Pgm to create a class Complex to add
dynamically created integer to a complex
number using Dynamic constructor.
Who is a friend ?
Ex : sample object;
object.getdata( );
Ex : sample object;
getdata(object) ;
Friend Functions
Example:
class myclass
{
int a, b;
Syntax:
public:
class class_name
friend int sum(myclass x);
{
void set_val(int i, int j);
//class definition
};
public:
friend rdt fun_name(formal parameters);
};
Code Snippet
class demo
{
int x ;
public :
demo(int xxx)
{ int main( )
x = xxx;
}
{
friend void display(demo) ; demo d(5);
}; display(d);
void display(demo d1) return 0;
}
{
cout<<dd1.x;
}
Friend function
• 3) Friend can access the private or protected members of the class in which they
are declared to be friend, but they can use the members for a specific object.
• 5) Friends, can be friend of more than one class, hence they can be used for
message passing between the classes.
• 6) Friend can be declared anywhere (in public, protected or private section) in the
class.
Program for Implementation
Pgm to create a class ACCOUNTS with function
read() to input sales and purchase details.
Create a Friend function to print total tax to
pay. Assume 4% of profit is tax.
Friend Class
#include <iostream>
class MyClass
{
private:
int Secret;
public:
MyClass() : Secret(0){}
void printMember()
{
cout << Secret << endl;
}
};
Friend Class
class SecondClass
{
public:
void change( MyClass& yourclass, int x )
{
yourclass.Secret = x;
}
};
void main()
{
MyClass my_class;
SecondClass sec_class;
my_class.printMember();
sec_class.change( my_class, 5 );
my_class.printMember();
}
Arrays of Objects
• Several objects of the same class can be
declared as an array and used just like an array
of any other data type.
#include <iostream.h>
const int MAX =8;
class Student
{
private: int roll;
char *name;
public:
void read_data( )
{
cout << "\n Enter the RollNo:";
cin >> roll;
cout << "\n Enter the name:";
cin >> name;
}
Example Of Array Of Objects
void print_data( )
{
cout << “Students Roll No is " << roll << "and name
is" << name << endl;
}
}; //class Detail ends
void main()
{
Student st[MAX]; //Array of objects of Detail class
int n=0;
Example Of Array Of Objects
char ans;
do
{
cout << "Enter the Info of Student ::" << n+1;
st[n++].read_data( );
cout << "Enter another (y/n)?: " ;
cin >> ans;
} while ( ans != 'n' );
for (int j=0; j<n; j++)
{
cout << "\n Info of Employee " << j+1<<“ is:: ”;
st[j].print_data( );
}
} // main ends
Class Objects
33, Joseph
• Avoridrreayad_odaftaO
( ) bjects
St[0]
ex: Student st[8]; St[1]
void print_data( )
St[2]
S t[0]
24, Sak sh i St[3]
void read_data( ) St[4]
void print_data( )
St[5]
St[6]
St[4] St[7]
Program for Implementation
Pgm to create a class STUDENT with
properties: rollno, name, IAmarks for 6
subjects, EndExamMarks for 6 subjects. Create
function read() to read the details of student,
calc_percent() to calculate the percentage
marks for each student and show() to display
the details of all students. Assume the
following things to calculate percentage:
Total_sub_marks = IAmarks + EndExamMarks
& Total_marks = Addition of Total_sub_marks
of 6 subjects.
Pointers to Objects
student st; 51, Rajesh
2FCD54
ptr st
Pointers to Objects
“Pointers can be defined to hold the address
of an object, which is created statically or
dynamically”.
33, Joseph Statically created object:
student *stp;
void read_data( )
stp = &st;
void print_data( )
Dynamically created object:
student *stp;
st stp = new student;
2FCDA4
Pointers to Objects
• Accessing Members of objects:
Syntax:
ptr_ob j member_name;
ptr_obj memberfunction_name( );
Example:
stp st_name;
stp read_data ( );
New and delete operators
setprecision ( ) / precision( )
• Select output precision, i.e., number of significant digits to be
printed.
• Example:
cout << setprecision (2) ; // two significant digits
OR
cout.precision(2);
setw ( )
• Specify the field width (Can be used on input or output, but
only applies to next insertion or extraction).
• Example:
cout << setw (4) ; // field is four positions wide
Manipulators
setw ( )
• Specify the field width (Can be used on input or output, but
only applies to next insertion or extraction).
• Example:
cout << setw (4) ; // field is four positions wide
Manipulators
• There are various flags for trailing zeros and decimal points,
justification, number base, floating point representation, and
so on.
Manipulators
ios::basefield
ios::dec use base ten
ios::oct use base eight
ios::hex use base sixteen
Manipulators
ios::floatfield
ios::fixed use fixed number of digits
ios::scientific use "scientific" notation
ios::adjustfield
ios::left use left justification
ios::right use right justification
ios::internal left justify the sign, but right
justify the value
Manipulators
.setf ( )
• Allows the setting of an I/O stream format flag.
• Examples:
// To show the + sign in front of positive numbers
cout.setf (ios::showpos) ;
.precision ( ) ;
• Select output precision, i.e., number of significant digits to be
printed.
• Example:
cout.precision (2) ; // two significant digits
.width ( ) ;
• Specify field width. (Can be used on input or output, but only
applies to next insertion or extraction).
• Example:
cout.width (4) ; // field is four positions wide
Manipulators