UNIT 1 Oodp
UNIT 1 Oodp
UNIT 1 Oodp
UNIT-1
Topic : PROCEDURAL AND OBJECT
ORIENTED PROGRAMMING
• The main program coordinates calls to procedures
and hands over appropriate data as parameters.
Procedure Oriented Programming Language
C function aspects Syntax
Eg : add(5,10);
Features of Procedure Oriented Programming
Language
• Smaller programs - A program in a procedural
language is a list of instructions.
• Larger programs are divided in to smaller programs
known as functions.
• Each function has a clearly defined purpose and a
clearly defined interface to the other functions in the
program.
• Data is Global and shared by almost all the functions.
• Employs Top Down approach in Program Design.
Examples of Procedure Oriented
Programming Language
• COBOL
• FORTRAN
•C
Sample COBOL Program(Procedure Oriented)
IDENTIFICATION DIVISION.
PROGRAM-ID.
DATA DIVISION.
WORKING-STORAGE SECTION.
77 A PIC 9999.
77 B PIC 9999.
77 ANS PIC 999V99.
PROCEDURE DIVISION.
MAIN-PARA.
DISPLAY \”--------------------------------\”.
DISPLAY \” ENTER A\”
ACCEPT A. * command line argument
DISPLAY \”ENTER B\”.
ACCEPT B.
DISPLAY \”----------------------------------\”.
ADD-PARA.
ADD A B GIVING ANS.
DISPLAY \”-------------------------------------\”.
DISP-PARA.
DISPLAY \”A IS \” A.
DISPLAY \”B IS \” B.
DISPLAY \”ADDITION -\” ANS.
STOP RUN. * to stop the program
Disadvantages of Procedural
Programming Language
Unrestricted access
• functions have unrestricted access to global data.
Real-world modeling
• unrelated (separated) functions and data, the basis
of the procedural paradigm, provide a poor model
of the real world.
• Complex real-world objects have both attributes
(data) and behavior (function).
Object-Oriented Concept
• The class is the repository for behavior associated with an object. That is, that
all objects that are instances of the same class can perform the same actions.
• Classes are organized into a singly rooted tree structure, called the inheritance
hierarchy.
• Memory and behavior associated with instances of a class are automatically
available to any class associated with a descendant in this tree structure.
Object-Oriented Programming vs.
Procedural Programming
• Programs are made up of modules, which are parts of a program that can
be coded and tested separately, and then assembled to form a complete
program.
• This is where you start with a problem (procedure) and then systematically
break the problem down into sub problems (sub procedures).
Object-Oriented Programming vs.
Procedural Programming
Program is divided into small parts Program is divided into small parts
called ‘Functions’ called ‘Objects’
GasMolecule ch4
GasMolecule co2 “pseudo-code”
spectrum = ch4.IR(1000,3500)
Name = co2.common_name
“Actually I made up the term ‘object-oriented’, and I can tell you I did
Characteristics of C++ not have C++ in mind.”
– Alan Kay (helped invent OO programming, the Smalltalk language, and the GUI)
C++ is…
Compiled.
A separate program, the compiler, is used to turn C++ source code into a form directly executed by
the CPU.
Strongly typed and unsafe
Conversions between variable types must be made by the programmer (strong typing) but can be
circumvented when needed (unsafe)
C compatible
call C libraries directly and C code is nearly 100% valid C++ code.
Capable of very high performance
The programmer has a very large amount of control over the program execution
Object oriented
With support for many programming styles (procedural, functional, etc.)
No automatic memory management
The programmer is in control of memory usage
“If you’re not at all interested in performance,
When to choose C++ shouldn’t you be in the Python room down the hall?”
― Scott Meyers (author of Effective Modern C++)
• For example
• cout<<“\n Enter the Marks”;
• cin>> ComputerNetworks>>OODP;
Reading and Writing Characters and Strings
• char marks;
• cin.get(marks);//The value for marks is read
• OR
• marks=cin.get();//A character is read and assigned to
marks
• string name;
• Cin>>name;
• string empname;
• cin.getline(empname,20);
• Cout<<“\n Welcome ,”<<empname;
Formatted Input and Output Operations
Formatted I/O
A variable is the content of a memory location that stores a certain value. A variable is identified or denoted by a variable
name. The variable name is a sequence of one or more letters, digits or underscore, for example: character_
Rules for defining variable name:
❖ A variable name can have one or more letters or digits or underscore for example character_.
❖ White space, punctuation symbols or other characters are not permitted to denote variable name.
❖ A variable name must begin with a letter.
❖ Variable names cannot be keywords or any reserved words of the C++ programming language.
❖ Data C++ is a case-sensitive language. Variable names written in capital letters differ from variable names with the same
name but written in small letters.
In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this
1
problem by using scope resolution operator (::), because this operator allows access to the global version of
a variable. New Operator
2 The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new
operator initializes the memory and returns the address of the newly allocated and initialized memory to the
Delete Operator
pointer variable.
3 Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided
.
delete operator by C++ language Member Operator
4 C++ permits us to define a class containing various types of data & functions as members. To access a
member using a pointer in the object & a pointer to the member.
Operator Precedence
Rank Operators Associativity
1 ++, --, +, -, !(logical complement) ,~(bitwise complement) ,(cast) Right
2 *(mul) , /(div), %(mod) Left
3 + , - (Binary) Left
4 >> , <<, >>> (Shift operator) Left
5 >, <, >=,<= Left
6 ==, != Left
7 & (Bitwise and) Left
8 ^ ( XOR) Left
9 | (Bitwise OR) Left
10 && (Logical and) Left
11 || (Logical OR) Left
12 Conditional Right
13 Shorthand Assignment Right
Pointers
Introduction
Void?
• When used in the declaration of a pointer, void specifies that the pointer is
"universal." If a pointer's type is void* , the pointer can point to any variable that's not
declared with the const or volatile keyword.
Real Time Example
How to use it
• P=∑//assign address of another variable
• cout<<∑ //to print the address of variable
• cout<<p;//print the value of variable
• Example of pointer
#include<iostream.h>
using namespace std;
int main()
{ int *p,sum=10;
p=∑
cout<<“Address of sum:”<<&sum<<endl;
cout<<“Address of sum:”<<p<<endl; Output:
Address of sum : 0X77712
cou<<“Address of p:”<<&p<<endl;
Address of sum: 0x77712
cout<<“Value of sum”<<*p; Address of p: 0x77717
} Value of sum: 10
Pointers and Arrays
• assigning the address of array to pointer don’t
use ampersand sign(&)
#include <iostream>
using namespace std;
int main(){
//Pointer declaration
int *p; OUTPUT:
//Array declaration 0
1
int arr[]={1, 2, 3, 4, 5, 6}; 2
//Assignment 3
p = arr; 4
5
for(int i=0; i<6;i++){ 6
cout<<*p<<endl;
//++ moves the pointer to next int position
p++;
}
return 0;
}
This Pointers
• this pointer hold the address of current
object
• int num;
• This->num=num;
This pointer Example
101 Sonoo 890000 102 Nakul 59000
101 Sonoo 890000 102 Nakul 59000
101 Sonoo 890000 102 Nakul 59000
101 Sonoo 890000
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary) Output: 101 Sonoo 890000
{
this->id = id; 102 Nakul 59000
this->name = name;
this->salary = salary;
}
void display() {
cout<<id<<" "<<name<<" "<<salary<<endl;
} };
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display(); e2.display(); return 0; }
Function using pointers
#include<iostream> void swap(int *a,int *b)
using namespace std; {
void swap(int *a ,int *b ); int c;
//Call By Reference c=*a;
int main() *a=*b;
{ *b=c;
int p,q; }
cout<<"\nEnter Two Number You Want To
Output:
Swap \n";
Enter Two Number You Want to
cin>>p>>q; Swap
swap(&p,&q); 10 20
cout<<"\nAfter Swapping Numbers Are Given After Swapping Numbers Are
below\n\n"; Given below
cout<<p<<" "<<q<<" \n"; 20 10
return 0;
}
MCQ
a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a
MCQ - Answer
a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a
MCQ-What is output of the following code?
#include <iostream>
using namespace std;
int main()
{
char arr[20];
int i;
for(i = 0; i < 10; i++)
*(arr + i) = 65 + i;
*(arr + i) = '\0';
cout << arr;
return(0);
}
MCQ - Answer
• Answer: ABCDEFGHIJ
Explanation: Each time we are assigning 65 +
i.
• In first iteration i = 0 and 65 is assigned.
• So it will print from A to J.
Type conversion and type casting
• Type conversion or typecasting of variables refers to changing a variable of one
data type into another.
• While type conversion is done implicitly, casting has to be done explicitly by the
programmer.
Implicit Type Conversion
The type conversion that is done automatically done by the compiler is known
as implicit type conversion. This type of conversion is also known as automatic
conversion.
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// integer x
char y = 'a’;
// character y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
int z = x + 1;
cout << "x = " << x << endl<< "y = " << y << endl<< "z = " << z << endl;
return 0;}
Type Casting
float sal=10000.00;
int income;
Income=int(sal);
Example for Explicit Type Conversion
#include <iostream>
using namespace std;
int main()
{ double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;}
Output:
Sum = 2
Class and objects - Features
Class
class className
{
data members
member functions
};
• Class is just a blue print, which declares and
Example
defines characteristics and behavior, namely class Room {
public:
data members and member functions
double length;
respectively. double breadth;
double height;
• All objects of this class will share these
characteristics and behavior. double calculateArea(){
return length * breadth;
• Class name must start with an uppercase
}
letter(Although this is not mandatory).
double calculateVolume(){
Example,
return length * breadth * height;
class Student }
};
Define a Class Type
- Data members Can be of any type, built-in or
user-defined.
This may be,
• non-static data member
Each class object has its own copy
Syntax:
static data_type datamember_name;
Here
static is the keyword.
data_type – int , float etc…
datamember_name – user defined
Static Data Member
Rectangle r1;
class Rectangle Rectangle r2;
{ Rectangle r3;
private:
int width;
int length; count
l); width
int area(); r3 length
}
Member Functions
• Used to
– access the values of the data members (accessor)
– perform operations on the data members
(implementor)
• Are declared inside the class body
• Their definition can be placed inside the class
body, or outside the class body
• Can access both public and private members of
the class
• Can be referred to using dot or arrow member
access operator
Member function
keyword Class Name
class Rectangle
{ int main()
private: {
int width, length; Rectangle r2; Object creation
public: r1.set(5,8); Inside the
void set (int w, int l); int x=r1.area(); function
member
int area() cout<<"x value in r1 "<<x;
function
{ r2.set(5,8);
inside the class return width*length; int x=r1.area();
} class name cout<<"x value in r2 "<<x;
}r1,; Member function
Object void Rectangle :: set (int w, int l) }
creation {
outside the class
width = w;
length = l;
}
scope operator
const member function
• The const member functions are the functions which are declared as constant in the program.
• The object called by these functions cannot be modified.
• It is recommended to use const keyword so that accidental changes to object are avoided.
• A const member function can be called by any type of object.
• Note: Non-const functions can be called by non-const objects only.
public :
void Write ( )
function definition
const ;
};
OBJECT
set of methods
Operations (member functions)
class Rectangle
main()
{ {
private: Rectangle r1;
Rectangle r2;
int width;
int length; r1.set(5, 8);
public: cout<<r1.area()<<endl;
};
Another Example
l); 5000
r1 r
int area(); width = 8
5 2
6000
length = 10
8 5000
???
};
Object Initialization
1. By Assignment
#include <iostream.h>
• Only work for public data
members
class circle
{ • No control over the operations
public: on data members
double radius;
};
int main()
{
circle c1; // Declare an instance of the class circle
c1.radius = 5; // Initialize by assignment
}
Object Initialization
2. By Public Member Functions
#include <iostream.h>
class circle
{
private:
double radius;
public:
void set (double r)
{radius = r;}
double get_r ()
{return radius;}
};
int main(void) {
circle c; // an object of circle class
c.set(5.0); // initialize an object with a public member function
cout << "The radius of circle c is " << c.get_r() << endl;
// access a private data member with an accessor
}
Declaration & Initialization of an Object
#include <iostream.h>
• Only work for public data
members
class circle
{ • No control over the operations
public: on data members
double radius;
};
int main()
{
circle c1; // Declare an instance of the class circle
c1.radius = 5; // Initialize by assignment
}
Examples
class Rectangle
main()
{ {
private: Rectangle r1;
int width; Rectangle r2;
int length; r1.set(5, 8);
public: cout<<r1.area()<<endl;
void set(int w, int l);
r2.set(8,10);
int area(); cout<<r2.area()<<endl;
}; }
Example: 2
#include <iostream>
using namespace std;
// create a class
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
Sample Exercises
1) Find whether the student is eligible for the current year placement from the
inputs student name, CGPA, gender (M/F), number of backlogs.
Implement the above by using object oriented programming concept.
3)Write a program that would print the information (name, year of joining,
salary, address) of three employees by creating a class named
'Employee'. The output should be as follows:
Name Year of joining Address
Robert 1994 64C- WallsStreat
Sam 2000 68D- WallsStreat
John 1999 26B- WallsStreat
Feature : Objects and Classes
Objects and Classes
•Class is a user defined data type, which holds its own data
members and member functions, which can be accessed and
used by creating instance of that class.
#include <iostream>
using std::cout; //this example “uses” only the necessary
using std::endl; // objects, not the entire std namespace
class Fraction {
public:
void assign (int, int); //member functions
double convert();
void invert();
void print();
private:
int num, den; //member data
};
Continued…
Using objects of a Class - Example
The main() function:
int main()
{
Fraction x;
x.assign (22, 7);
cout << "x = "; x.print();
cout << " = " << x.convert() << endl;
x.invert();
cout << "1/x = "; x.print(); cout << endl;
return 0;
}
Continued…
Defining a Class – Example
Class Implementation:
void Fraction::assign (int numerator, int denominator)
{
num = numerator;
den = denominator;
}
double Fraction::convert ()
{
return double (num)/(den);
}
void Fraction::invert()
{
int temp = num;
num = den;
den = temp;
}
void Fraction::print()
{
cout << num << '/' <
}< den;
Difference Between Class and Structure
void main() {
Distance d1,d2;
d1.setFeet(2);
d1.setInches(2.2);
d2.setFeet(3);
d2.setInches(3.3);
d1.iFeet++; // ??????
cout<<d1.getFeet()<<d1.getInches()<<d2.getFeet()<<d2.getInche
s()<<endl;
Scope Resolution Operator
• Communication(collaberation
)
• Sequence
• Interaction overview
• Timing
Class Diagram
SmokeAlarm
Responsibilities
CourseSchedule
Course
add(c : Course)
remove(c :
Course)
Dependency - Aggregation
Student Employee
TeachingAssistant
Generalization Relationships
Multilevel Inheritance
(Cont’d)
Relationships b/w Classes
Inheritance (Generalization)
• Lets say in our zoo, the only animals we have are tortoises, otters and Slow Loris
• We make 3 new classes: Tortoise, Otter and
Slow Loris
• These subclasses inherit all the attributes and
methods of the superclass
• We could add an attribute specific to Otter
in the Otter class
• The main advantage of inheritance is that
if we wanted to change or add an attribute
for all animals, we need not make change in
every sub class
• We just make the change to the base class ‘Animal’ class and it applies across all sub classes
Relationships b/w Classes
Abstraction
• In this example ‘Animal’ is the Abstract Class
• We will create instance for only the subclasses
• We wouldn’t instantiate the Animal class itself
• The Animal class is just a way to simplify things and keep the code “dry”
• To show that it is an Abstract class, we can write the name of the class in italics Animal or we
can enclose it like <<Animal>>
Relationships b/w Classes
Association
• If we had a class for Sea Urchin
we could draw an association
• Sea otter is a marine mammal in
the north Pacific Ocean
• They eat mostly hard-shelled invertebrates
including sea urchins.
ASSOCI
ATION
Aggregation ( (open diamond)
• It is a special type of association that specifies a whole and its parts, where a part can exist
outside the whose
• Lets take a group of tortoises, called creep
ASSOCIATION
A tortoise could leave the creep at any point and still
Exist on its own
An aggregation specifies a whole-part relationship between an
aggregate (a whole) and a constituent part, where the part can
exist independently from the aggregate. Aggregations are
denoted by a hollow-diamond adornment on the association.
Engine
Car
Transmission
Composition
• It is a special type of association that specifies a whole and its parts, where the part cannot
exist outside the whole
• Example: Let us say we have several different visitors centers in our zoo. And each of those
visitor centers has a lobby and a bathroom
• Now if one of our visitors centers was torn down, the lobby and the bathroom of that visitor
center are torn down as well.
• Composition : A child object cannot exist without its parent object
A composition indicates a strong ownership and coincident
lifetime of parts by the whole (i.e., they live and die as a
whole). Compositions are denoted by a filled-diamond
adornment on the association.
Scrollbar
1 1
Window Titlebar
1 1
Menu
1 1 .. *
Composition
• A restricted form of Aggregation in which two
entities (or you can say classes) are highly
dependent on each other.
• A human needs a heart to live and a heart needs a
human body to function on. In other words when
the classes (entities) are dependent on each other
and their life span are same (if one dies then
another one does too) then it’s a composition.
Multiplicity
• After specifying the type of association relationship by
connecting the classes, you can also declare the cardinality
between the associated entities. For example:
g>
rin
tak
es>
du
ld
he
0..8
is
1..*
teaches> Class
Instructor
Section
1..3 0..6
1..*
is
<works for
in
st
an
ce
of
>
1 sponsors>
1 1..*
Department Course
Questions
• From the previous diagram
– How many classes can a student take?
– Do you have to be registered in any classes to be a
student?
– Do I need to teach this class to be an Instructor?
Do I need to teach ANY classes?
1. What type of core-relationship is represented by the symbol in the figure below?
a) Aggregation
b) Dependency
c) Generalization
d) Association
Answer: a
2. Which core element of UML is being shown in the figure?
a) Node
b) Interface
c) Class
d) Component
Answer: d
3. What type of relationship is represented by Shape class and Square ?
a) Realization
b) Generalization
c) Aggregation
d) Dependency
Answer: b
4. Consider a directed line (->) from the relation ship set advisor to both entity sets
instructor and student. This indicates ___________ cardinality.
a. One to many
b. One to one
c. Many to many
d. Many to one
Answer: b
5. An entity set that does not have sufficient attributes to form a primary key is
termed as a ____
a. Strong entity set
b. Variant set
c. Weak entity set
d. Variable set
Answer: c
Association Relationships (Cont’d)
We can indicate the multiplicity of an association by adding
multiplicity adornments to the line denoting the association.
Student Instructor
1..*
Association Relationships (Cont’d)
The example indicates that every Instructor has one or more
Students:
Student Instructor
1..*
Association Relationships (Cont’d)
We can also indicate the behavior of an object in an association
(i.e., the role of an object) using rolenames.
membership
Student Team
1..* 1..*
Association Relationships
(Cont’d)
We can specify dual associations.
member of
1..* 1..*
Student Team
1 president of 1..*
Association Relationships
(Cont’d)
Associations can also be objects themselves, called link classes
or an association classes.
Registration
modelNumber
serialNumber
warrentyCode
Product Warranty
Association Relationships
(Cont’d)
A class can have a self association.
next
LinkedListNode
previous
Interfaces
An interface is a named set of
operations that specifies the behavior
<<interface>> of objects without showing their inner
ControlPanel structure. It can be rendered in the
model by a one- or two-compartment
rectangle, with the stereotype
<<interface>> above the interface
name.
A real world Example
A Simple C++ Program with class
Output
Topic : Feature Abstraction and
Encapsulation, Application of Abstraction and
Encapsulation
Abstraction
• Data abstraction allows a program to ignore the details of
how a data type is represented.
• public •: A public member is accessible from anywhere outside the class but within a
program.
• private : A private member variable or function cannot be accessed, or even viewed from
outside the class. Only the class and friend functions can access private members.
class ClassName
{
private:
// declare private members/methods here
public:
// declare public members/methods here
protected:
// declare protected members/methods here
};
•
Example 1: C++ public Access Specifier
#include <iostream>
int main()
using namespace std; {
class Sample // define a class Sample obj1; // declare a class object
{ cout << "Enter your age: ";
public: // public elements
int age; // store input in age of the obj1 object
cin >> obj1.age;
void displayAge()
{ obj1.displayAge(); // call class function
cout <<
•
"Age = " << age << endl; return 0;
} }
};
Output:
class Sample
{ int main()
private: // private elements {
int age; int ageInput;
Sample obj1;
public: // public elements cin >> obj1.age; // error
void displayAge(int a) cout << "Enter your age: ";
{ cin >> ageInput;
age = a; obj1.displayAge(ageInput);
•
cout << "Age = " << age << endl; return 0;
} }
};
Output:
};
Output:
1. UML diagram that shows the interaction between users and system, is known as
A. Activity diagram
B. E-R diagram
C. Use case diagram
D. Class diagram
Answer:C