SlideShare a Scribd company logo
21CSC101T OBJECT ORIENTED DESIGN
AND PROGRAMMING
Unit-1 - Introduction to OOPS
1
Dr.M.Sivakumar, AP/NWC
Course Outcomes (CO)
At the end of this course, learners will be able to:
• CO-1: Create programs using object-oriented approach and
design methodologies
• CO-2: Construct programs using method overloading and
operator overloading
• CO-3: Create programs using inline, friend and virtual
functions, construct programs using standard templates
• CO-4: Construct programs using exceptional handling and
collections
• CO-5: Create Models of the system using UML Diagrams
2
Dr.M.Sivakumar, AP/NWC
Unit-1 - Introduction to OOPS
1. Object-Oriented Programming - Features of C++
2. I/O Operations, Data Types, Variables-Static, Constants,
Pointers
3. Type Conversions - Conditional and looping statements
4. Arrays - C++ 11 features
5. Class and Objects, Abstraction and Encapsulation,
6. Access Specifiers, Methods
7. UML Diagrams Introduction - Use Case Diagram, Class
Diagram.
8. Practice questions from elab
9. Quiz/Puzzles/Review Questions
3
Dr.M.Sivakumar, AP/NWC
SESSION-01
Introduction to Object-Oriented Programming, Features of C++
Dr.M.Sivakumar, AP/NWC 4
OBJECT-ORIENTED PROGRAMMING
5
Dr.M.Sivakumar, AP/NWC
Programming Languages
• Programming a computer involves writing instructions that
enable a computer to carry out a single task or a group of tasks
• Writing these sets of instructions, which are known as programs
or software, requires using a computer programming language
and resolving any errors in the instructions so that the programs
work correctly
• Programs are also frequently called application programs
• Simply applications, because you apply them to a task such as
preparing payroll checks, creating inventory reports, or—as in
the case of game programs—even entertaining someone
6
Dr.M.Sivakumar, AP/NWC
Programming Languages
• learning a computer programming language requires learning
both vocabulary and syntax.
• The rules of any language make up its syntax.
• When you write programs, you write program statements that
are instructions that are similar to English-language sentences.
7
Dr.M.Sivakumar, AP/NWC
Types of Programming Languages
• Machine level Language
• Assembly level Language
• High level Language
–Procedure oriented programming(POP) language
–Object oriented programming(OOP) language.
8
Dr.M.Sivakumar, AP/NWC
Procedure Oriented Programming Language
• Drawbacks
– Global data access
– It does not model real word problem very well
– No data hiding
9
Dr.M.Sivakumar, AP/NWC
Characteristics of procedure oriented
programming
• Emphasis is on doing things(algorithm)
• Large programs are divided into smaller programs
known as functions
• Most of the functions share global data
• Data move openly around the system from function to
function
• Function transforms data from one form to another
• Employs top-down approach in program design
10
Dr.M.Sivakumar, AP/NWC
Object Oriented Programming
• Object oriented programming as an
approach that provides a way of
modularizing programs by creating
partitioned memory area for both data and
functions that can be used as templates for
creating copies of such modules on demand
11
Dr.M.Sivakumar, AP/NWC
Object Oriented Programming
12
Dr.M.Sivakumar, AP/NWC
Object Oriented Programming
13
Dr.M.Sivakumar, AP/NWC
Object Oriented Programming
• Combine data and functions into object.
(Member Data & Member Functions)
• Member functions are also called methods.
• Member data are hidden within member
functions.
• Data Encapsulation & Data Hiding.
• Objects interact by sending messages to
each other.
14
Dr.M.Sivakumar, AP/NWC
Object Oriented Programming
Vs Procedural Oriented Programming
Procedure Oriented Programming Object Oriented Programming
program is divided into small parts
called functions
program is divided into parts called objects.
Importance is not given to data but to
functions as well as sequence of
actions to be done.
Importance is given to the data rather than
procedures or functions because it works as a real
world.
follows Top Down approach OOP follows Bottom Up approach.
It does not have any access specifier OOP has access specifiers named
Public, Private, Protected, etc
Data can move freely from
function to function in the system
objects can move and communicate with
each other through member functions.
It does not have any proper way for hiding data so
it is less secure
OOP provides Data Hiding so provides more
security
Overloading is not possible In OOP, overloading is possible in the form of
Function Overloading and Operator
Overloading.
15
Dr.M.Sivakumar, AP/NWC
Basic concepts of OOPS
1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing
16
Dr.M.Sivakumar, AP/NWC
Objects
• Software objects model real-world objects or abstract
concepts.
dog, bicycle, queue
• Real-world objects have states and behaviors.
Dogs' states: name, color, breed, hungry
Dogs' behaviors: barking, fetching
• How do software objects implement real-world objects?
Use variables/data to implement states.
Use methods/functions to implement behaviors.
• An object is a software bundle of variables and related methods.
17
Dr.M.Sivakumar, AP/NWC
Class
• A class is a blueprint or prototype defining the variables
and methods common to all objects of a certain kind.
• An object is an instance of a certain class.
• After you have created a class, you must create an
instance of it before you can use.
• Class variables and class methods.
18
Dr.M.Sivakumar, AP/NWC
Class and Objects
19
Dr.M.Sivakumar, AP/NWC
Class and Objects
20
Dr.M.Sivakumar, AP/NWC
Class and Objects
21
Dr.M.Sivakumar, AP/NWC
Data abstraction and encapsulation
• It is a mechanism that binds together code and the
data it manipulates, and keeps both safe from
outside interference and misuse
22
Dr.M.Sivakumar, AP/NWC
Data abstraction and encapsulation
23
Dr.M.Sivakumar, AP/NWC
Data abstraction and encapsulation
• Encapsulation is as a protective wrapper that prevents the code and
data from being arbitrarily accessed by other code defined outside
the wrapper
• Access to the code and data inside the wrapper is tightly controlled
through a well-defined interface
24
Dr.M.Sivakumar, AP/NWC
Inheritance
• Inheritance is the process by which one object acquires the
properties of another object
25
Dr.M.Sivakumar, AP/NWC
Inheritance
26
Dr.M.Sivakumar, AP/NWC
Inheritance
27
Dr.M.Sivakumar, AP/NWC
Polymorphism
• Polymorphism (from Greek, meaning “many forms”) is a feature that
allows one interface to be used for a general class of actions
• The specific action is determined by the exact nature of the situation
28
Dr.M.Sivakumar, AP/NWC
Polymorphism
29
Dr.M.Sivakumar, AP/NWC
Dynamic binding
30
Dr.M.Sivakumar, AP/NWC
Message Passing
 What are Messages?
 Software objects interact and communicate with each
other by sending messages to each other. 31
Dr.M.Sivakumar, AP/NWC
Benefits of Object-Oriented programming
• Reuse of existing code
• Improved maintainability
• Often a ‘natural’ way to describe a system
32
Dr.M.Sivakumar, AP/NWC
Applications of Object Oriented Programming
• Client-Server Systems
• Real-Time System
• Object-Oriented Databases
• Simulation and modelling
• AI and expert systems
• Neural networks and parallel programming
33
Dr.M.Sivakumar, AP/NWC
Dr.M.Sivakumar, AP/NWC 34
Introduction to C++
• C++ is a general-purpose programming language that was
developed as an extension of the C programming language with
object-oriented programming features
• C++ was invented by Bjarne Stroustrup in 1979, at Bell
Laboratories in Murray Hill, New Jersey
• C++ is derived from the C language
• C++ provides a combination of low-level features for systems
programming and high-level features for application
development.
• C++ is also the language from which both Java and C# are
derived
35
Dr.M.Sivakumar, AP/NWC
Sample C++ Program
36
Dr.M.Sivakumar, AP/NWC
Features of C++
• Object-Oriented Programming (OOP)
• Procedural Programming
• Standard Template Library (STL)
• Memory Management
• Performance
• Portability with relatively few modifications
• Wide Usage
37
Dr.M.Sivakumar, AP/NWC
Difference between C and C++
C C++
Procedural programming language
Supports both procedural programming (like C)
and object-oriented programming (OOP)
Simpler syntax
Extends the syntax of C by adding new keywords
and features
Memory management is typically done manually
using functions like malloc and free
operators like new and delete for dynamic
memory allocation.
Does not have a standard template library Includes the Standard Template Library (STL)
Does not support function overloading Allows function overloading
Does not have the concept of namespaces Introduces namespaces
printf and scanf for input and output cout for output and cin for input 38
Dr.M.Sivakumar, AP/NWC
SESSION-02
I/O Operations, Data Types, Variables -Static, Constants - Pointers
Dr.M.Sivakumar, AP/NWC 39
I/O OPERATIONS, DATA TYPES, VARIABLES-
STATIC, CONSTANTS
Dr.M.Sivakumar, AP/NWC 40
I/O Operations
• C++ I/O operation occurs in streams, which involve transfer of
information into byte
• It’s a sequences of bytes
• Stream involved in two ways
• It is the source as well as the destination of data
• C++ programs input data and output data from a stream.
• Streams are related with a physical device such as the monitor or
with a file stored on the secondary memory.
• In a text stream, the sequence of characters is divided into lines,
with each line being terminated.
• With a new-line character (n) . On the other hand, a binary stream
contains data values using their memory representation.
41
Dr.M.Sivakumar, AP/NWC
I/O Operations
42
Dr.M.Sivakumar, AP/NWC
Stream in C
Text Stream Binary Stream
Cascading of Input or Output Operators
43
Dr.M.Sivakumar, AP/NWC
• << operator –It can use multiple times in the same line.
• Its called Cascading
• Cout ,Cin can cascaded
• For example
• cout<<“n Enter the Marks”;
• cin>> ComputerNetworks>>OODP;
Reading and Writing Characters and Strings
44
Dr.M.Sivakumar, AP/NWC
• 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
45
Dr.M.Sivakumar, AP/NWC
Formatted I/O
I/O class function and
flages
Manipulators
Example
46
Dr.M.Sivakumar, AP/NWC
#include<iostream.h>
#define PI 3.14159
main()
{
cout.precision(3);
cout.width(10);
cout.fill(‘*’);
cout<<PI;
}
Output
*****3.142
Formatting with flags
47
Dr.M.Sivakumar, AP/NWC
• The setf() is a member function of the ios class that is used to set
flags for formatting output.
• Syntax:
cout.setf(flag, bit-field)
• Here, flag defined in the ios class specifies how the output should
be formatted
• bit-field is a constant (defined in ios ) that identifies the group to
which the formatting flag belongs to.
• There are two types of setf()—one that takes both flag and bit-
fields and the other that takes only the flag .
Formatting with flags
48
Dr.M.Sivakumar, AP/NWC
Formatting Output Using Manipulators
49
Dr.M.Sivakumar, AP/NWC
Data Types in C++
50
Dr.M.Sivakumar, AP/NWC
Variables
51
Dr.M.Sivakumar, AP/NWC
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.
Static Variables
Local Variables Instance variables
01
02
03
Constant Variables
04
Variables
52
Dr.M.Sivakumar, AP/NWC
Local Variables Instance Variables Static Variables Constant Variables
Local variable: These are the
variables which are declared within
the method of a class.
Example:
public class Car
{
public:
// Method
void display(int m)
{
// Created a local variable
int model=m;
cout<<model;
}
};
Static variables: Static variables are
also called as class variables. These
variables have only one copy that is
shared by all the different objects in
a class.
Example:
class Car
{
public:
//Static variable
static int tyres;
void init()
{
tyres=4;
}
};
Instance variable: These are the
variables which are declared in a
class but outside a method,
constructor or any block.
Example:
public class Car
{
private:
// Created an instance variable
String color;
Car(String c)
{
color=c;
}
};
Constant is something that
doesn't change. In C language
and C++ we use the keyword
const to make program elements
constant.
Example:
const int i = 10;
void f(const int i);
class Test
{
const int i;
};
CONSTANTS
• Constants are identifiers whose value does not change. While variables can
change their value at any time, constants can never change their value.
• Constants are used to define fixed values such as Pi or the charge on an
electron so that their value does not get changed in the program even by
mistake.
• A constant is an explicit data value specified by the programmer.
• The value of the constant is known to the compiler at the compile time.
Dr.M.Sivakumar, AP/NWC 53
Declaring Constants
• Rule 1 Constant names are usually written in capital letters to visually distinguish them
from other variable names which are normally written in lower case characters.
• Rule 2 No blank spaces are permitted in between the # symbol and define keyword.
• Rule 3 Blank space must be used between #define and constant name and between
constant name and constant value.
• Rule 4 #define is a preprocessor compiler directive and not a statement. Therefore, it does
not end with a semi-colon.
Dr.M.Sivakumar, AP/NWC 54
Operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Dr.M.Sivakumar, AP/NWC 55
Arithmetic Operators
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9
Dr.M.Sivakumar, AP/NWC 56
Relational Operators
Operator Description Example
==
Checks if the values of two operands are equal or not, if yes then condition
becomes true.
(A == B) is not true.
!=
Checks if the values of two operands are equal or not, if values are not equal
then condition becomes true.
(A != B) is true.
>
Checks if the value of left operand is greater than the value of right operand,
if yes then condition becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less than the value of right operand, if
yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of
right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true.
(A <= B) is true.
Dr.M.Sivakumar, AP/NWC 57
Logical Operators
Operator Description Example
&&
Called Logical AND operator. If both the operands are non-zero,
then condition becomes true.
(A && B) is false.
||
Called Logical OR Operator. If any of the two operands is non-zero,
then condition becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses the logical state of its
operand. If a condition is true, then Logical NOT operator will make
false.
!(A && B) is true.
Dr.M.Sivakumar, AP/NWC 58
Bitwise Operators
Operator Description Example
&
Binary AND Operator copies a bit to the result if it exists in
both operands.
(A & B) will give 12 which is 0000
1100
| Binary OR Operator copies a bit if it exists in either operand.
(A | B) will give 61 which is 0011
1101
^
Binary XOR Operator copies the bit if it is set in one operand
but not both.
(A ^ B) will give 49 which is 0011
0001
~
Binary Ones Complement Operator is unary and has the effect
of 'flipping' bits.
(~A ) will give -61 which is 1100 0011
in 2's complement form due to a
signed binary number.
<<
Binary Left Shift Operator. The left operands value is moved
left by the number of bits specified by the right operand.
A << 2 will give 240 which is 1111
0000
>>
Binary Right Shift Operator. The left operands value is moved
right by the number of bits specified by the right operand.
A >> 2 will give 15 which is 0000 1111
Dr.M.Sivakumar, AP/NWC 59
Assignment Operators
Operator Description Example
=
Simple assignment operator, Assigns values from right side
operands to left side operand.
C = A + B will assign value of A + B
into C
+=
Add AND assignment operator, It adds right operand to the left
operand and assign the result to left operand.
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand
from the left operand and assign the result to left operand.
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand
with the left operand and assign the result to left operand.
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with
the right operand and assign the result to left operand.
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two
operands and assign the result to left operand.
C %= A is equivalent to C = C % A
Dr.M.Sivakumar, AP/NWC 60
Misc Operators
Operator Description Example
sizeof() sizeof operator returns the size of a variable.
sizeof(a), where ‘a’ is integer, and will
return 4.
? :
Conditional operator (?). If Condition is true then it returns
value of X otherwise returns value of Y.
,
Comma operator causes a sequence of operations to be
performed. The value of the entire comma expression is the
value of the last expression of the comma-separated list.
. and -> Member operators are used to reference individual members
of classes, structures, and unions.
Cast Casting operators convert one data type to another. int(2.2000) would return 2.
& Pointer operator & returns the address of a variable.
&a; will give actual address of the
variable.
* Pointer operator is pointer to a variable. *var; will pointer to a variable var.
Dr.M.Sivakumar, AP/NWC 61
Operators Precedence in C++
Dr.M.Sivakumar, AP/NWC 62
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Special Operators
Dr.M.Sivakumar, AP/NWC 63
1
2
3
4
In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by using scope
resolution operator (::), because this operator allows access to the global version of a variable.
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 pointer variable.
Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided delete operator by C++
language.
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.
Scope resolution operator
new Operator
delete Operator
Member Operator
Pointers
• Pointers are symbolic representation of addresses.
• They enable programs to simulate call-by-reference as well as to create and manipulate
dynamic data structures.
• Syntax data_type *pointer_variable;
• Example
int *p,sum;
Assignment
• integer type pointer can hold the address of another int variable
• To assign the address of variable to pointer-ampersand symbol (&)
p=&sum;
this pointer
hold the adderss of current object
int num;
this->num=num;
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.
64
Dr.M.Sivakumar, AP/NWC
Pointers
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
Steps:
(a) We define a pointer variable.
(b) Assign the address of a variable to a pointer.
(c) Finally access the value at the address available in the
pointer variable.
65
Dr.M.Sivakumar, AP/NWC
Real Time Example
66
Dr.M.Sivakumar, AP/NWC
How to use it
#include <iostream>
using namespace std;
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
67
Dr.M.Sivakumar, AP/NWC
Output:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Pointers and Arrays
#include <iostream>
using namespace std;
int main()
{
//Pointer declaration
int *p;
//Array declaration
int arr[]={1, 2, 3, 4, 5, 6};
//Assignment
p = arr;
for(int i=0; i<6;i++)
{
cout<<*p<<endl;
//++ moves the pointer to next int position
p++;
}
return 0;
}
68
Dr.M.Sivakumar, AP/NWC
OUTPUT:
0
1
2
3
4
5
6
this Pointers
• this pointer hold the address of current object
• int num;
• This->num=num;
69
Dr.M.Sivakumar, AP/NWC
this Pointers Example
#include <iostream>
using namespace std;
class Employee
{
int id; //data member (also instance variable)
char name[20]; //data member(also instance variable)
float salary;
public:
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
}; 70
Dr.M.Sivakumar, AP/NWC
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;
}
Output:
101 Sonoo 890000
102 Nakul 59000
Function using pointers
71
Dr.M.Sivakumar, AP/NWC
#include<iostream>
using namespace std;
void swap(int *a ,int *b );
//Call By Reference
int main()
{
int p,q;
cout<<"nEnter Two Number You Want To Swap n";
cin>>p>>q;
swap(&p,&q);
cout<<"nAfter Swapping Numbers Are Given belownn";
cout<<p<<" "<<q<<" n";
return 0;
}
void swap(int *a,int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
}
Output:
Enter Two Number You Want to Swap
10 20
After Swapping Numbers Are Given below
20 10
MCQ
72
Dr.M.Sivakumar, AP/NWC
What will happen in the following C++ code snippet?
1)Int a=100, b=200;
2) Int *p=&a, *q=&b;
3) p=q;
Choose the correct one.
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
73
Dr.M.Sivakumar, AP/NWC
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
74
Dr.M.Sivakumar, AP/NWC
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
75
Dr.M.Sivakumar, AP/NWC
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.
SESSION-03
Type Conversions,
Conditional and Looping Statements
Dr.M.Sivakumar, AP/NWC 76
Type Conversions
• Type conversion is the process that converts the predefined data type of
one variable into an appropriate data type.
• Type conversion can be done in two ways in C++
1. Implicit type conversion
2. Explicit type conversion
77
Dr.M.Sivakumar, AP/NWC
Implicit Type Conversions
• The type conversion that is done automatically done by the compiler
• This type of conversion is also known as automatic conversion
#include <iostream>
using namespace std;
int main ()
{
// assign the integer value
int num1 = 25;
// declare a float variable
float num2;
// convert int value into float variable using implicit conversion
num2 = num1;
cout << " The value of num1 is: " << num1 << endl;
cout << " The value of num2 is: " << num2 << endl;
return 0;
}
78
Dr.M.Sivakumar, AP/NWC
Output:
The value of num1 is: 25
The value of num2 is: 25
Explicit Type Conversions (or)
Type Casting
• Conversions that require user intervention to change the data type of one
variable to another
• Hence, it is also known as typecasting
• The explicit type conversion is done in two ways:
– Explicit conversion using the cast operator
– Explicit conversion using the assignment operator
Dr.M.Sivakumar, AP/NWC 79
1. Explicit conversion using the cast operator
#include <iostream>
using namespace std;
int main ()
{
float f2 = 6.7;
// use cast operator to convert data from one type to another
int x = static_cast <int> (f2);
cout << " The value of x is: " << x;
return 0;
}
Dr.M.Sivakumar, AP/NWC 80
2. Explicit conversion using the assignment operator
#include <iostream>
using namespace std;
int main ()
{
// declare a float variable
float num2;
// initialize an int variable
int num1 = 25;
// convert data type from int to float
num2 = (float) num1;
cout << " The value of int num1 is: " << num1 << endl;
cout << " The value of float num2 is: " << num2 << endl;
return 0;
}
Dr.M.Sivakumar, AP/NWC 81
Conditional and looping statements
• if…else
• switch
• for
• while
• do…while
• break
• continue
82
Dr.M.Sivakumar, AP/NWC
SESSION-04
Arrays - C++ 11 features
Dr.M.Sivakumar, AP/NWC 83
Arrays
• Declaring Arrays
type arrayName [ arraySize ];
• Initializing Arrays
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
balance[4] = 50.0;
• Accessing Array Elements
84
Dr.M.Sivakumar, AP/NWC
Accessing Array Elements
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main ()
{
int n[ 10 ]; // n is an array of 10 integers
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ )
{
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;
// output each array element's value
for ( int j = 0; j < 10; j++ )
{
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}
return 0;
}
85
Dr.M.Sivakumar, AP/NWC
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
C++ version 11 features
• Simple and User Friendly
• Object Oriented Programming
• Platform Dependent
• Structured Programming Language
• Mid-Level Programming Language
• Rich Library
• Case-Sensitive
• Dynamic Memory Allocation
• Memory Management
• Powerful and Fast
86
Dr.M.Sivakumar, AP/NWC
SESSION-05
Class and Objects, Abstraction and
Encapsulation
Dr.M.Sivakumar, AP/NWC 87
CLASS AND OBJECTS, ABSTRACTION AND
ENCAPSULATION
88
Dr.M.Sivakumar, AP/NWC
Class
• Class is a user defined data type, defined using keywork class.
• It holds its own data members and member functions,
• It can be accessed and used by creating instance of that class.
• The variables inside class definition are called as data members and
the functions are called member functions
class className
{
data members
member functions
};
Dr.M.Sivakumar, AP/NWC 89
Syntax of Class
class ClassName
{
public:
// Member variables (attributes)
dataType memberVariable1;
dataType memberVariable2;
// ...
// Member functions (methods)
returnType methodName1(ParameterType1 parameter1, ParameterType2 parameter2)
{
// Function body
}
returnType methodName2(ParameterType3 parameter3)
{
// Function body
}
// ...
};
90
Dr.M.Sivakumar, AP/NWC
Class
• Class is just a blue print, which declares and defines
characteristics and behavior, namely data members
and member functions respectively.
• All objects of this class will share these characteristics
and behavior.
• Class name must start with an uppercase
letter(Although this is not mandatory).
Example,
class Student
91
Dr.M.Sivakumar, AP/NWC
Example
class Room
{
public:
double length;
double breadth;
double height;
double calculateArea()
{
return length * breadth;
}
double calculateVolume()
{
return length * breadth * height;
}
};
Define a class
Dr.M.Sivakumar, AP/NWC 92
Data Member
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
• static data member
Acts as a global variable
Dr.M.Sivakumar, AP/NWC 93
Static Data Member
• Static data member is declared using the static keyword.
• There is only one copy of the static data member in the class. All the objects share
the static data member.
• The static data member is always initialized to zero when the first class object is
created.
Syntax:
static data_type datamember_name;
Here
static is the keyword.
data_type – int , float etc…
datamember_name – user defined Dr.M.Sivakumar, AP/NWC 94
Static Data Member
#include <iostream>
using namespace std;
class Account
{
public:
int accno; //data member (also instance variable)
string name;
static int count;
Account(int accno, string name) // Constructor Function
{
this->accno = accno;
this->name = name;
count++;
}
void display()
{
cout<<accno<<" "<<name<<endl;
}
};
Dr.M.Sivakumar, AP/NWC 95
int Account::count=0;
int main(void)
{
Account a1 =Account(201, "Sanjay");
//creating an object of Account
Account a2=Account(202, "Nakul");
Account a3=Account(203, "Ranjana");
a1.display();
a2.display();
a3.display();
cout<<"Total Objects are: "<<Account::count;
return 0;
}
Output:
201 Sanjay
202 Nakul
203 Ranjana
Total Objects are: 3
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
Dr.M.Sivakumar, AP/NWC 96
Member Functions
Dr.M.Sivakumar, AP/NWC 97
class Rectangle
{
private:
int width, length;
public:
void set (int w, int l);
int area()
{
return width*length;
}
};
void Rectangle :: set (int w, int l)
{
width = w;
length = l;
}
member function
keyword Class Name
inside the class
outside the class
class name
Member function
int main()
{
Rectangle r2;
r1.set(5,8);
int x=r1.area();
cout<<"x value in r1 "<<x;
r2.set(5,8);
int x=r1.area();
cout<<"x value in r2 "<<x;
}
Object
creation
Inside the
function
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.
Syntax:
datatype function_name() const
{
}
Dr.M.Sivakumar, AP/NWC 98
const member function
#include<iostream>
using namespace std;
class sample
{
private:
int val;
public:
sample(int x = 0)
{
val = x;
}
int getValue() const
{
return val;
}
};
Dr.M.Sivakumar, AP/NWC 99
int main()
{
const sample s(20);
sample s1(2);
cout << "The value using object d : " << s.getValue();
cout << "nThe value using object d1 : " <<
s1.getValue();
return 0;
}
SESSION-06
Access Specifiers, Methods
Dr.M.Sivakumar, AP/NWC 100
Access Specifiers
• One of the main features of object-oriented programming languages
such as C++ is data hiding.
• Data hiding refers to restricting access to data members of a class.
• This is to prevent other functions and classes from tampering with
the class data.
Definition :
The access specifiers of C++ allows us to determine which class
members are accessible to other classes and functions, and which
are not.
Types of access specifiers
• Public members can be accessed from anywhere
in the program, including outside the class.
Public
• Private members can only be accessed from
within the class itself.
Private
• Protected members can be accessed from within
the class itself, from derived classes and from
friend function
Protected
Example: public
#include<iostream>
using namespace std;
class student
{
public:
char name[20];
int age;
void display();
};
int main()
{
student s1;
cout<<"Enter name:";
cin>>s1.name;
cout<<"Enter age:";
cin>>s1.age;
s1.display();
return 0;
}
void student::display()
{
cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age;
}
Output:
Enter name:raja
Enter age:20
Name:raja
Age:20
Example: private
#include<iostream>
using namespace std;
class student
{
private:
char name[20];
int age;
public:
void getdata();
void display();
};
int main()
{
student s1;
//cin>>s1.name;
//cin>>s1.age;
s1.getdata();
s1.display();
return 0;
}
void student::getdata()
{
cout<<"Enter name:";
cin>>name;
cout<<"Enter age:";
cin>>age;
}
void student::display()
{
cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age;
}
Output:
Enter name:raja
Enter age:21
Name:raja
Age:21
Example: protected
#include<iostream>
using namespace std;
class person
{
protected:
char name[20];
int age;
};
class student: public person
{
public:
void getdata();
void display();
};
int main()
{
student s1;
s1.getdata();
s1.display();
return 0;
}
void student::getdata()
{
cout<<"Enter name:";
cin>>name;
cout<<"Enter age:";
cin>>age;
}
void student::display()
{
cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age;
}
Output:
Enter name:raja
Enter age:22
Name:raja
Age:22
Syntax of Declaring Access Specifiers in C++
class ClassName
{
private:
// declare private members/methods here
public:
// declare public members/methods here
protected:
// declare protected members/methods here
};
Conclusion
• If any sensitive information that, when leaked or tampered with,
can cause trouble, always make sure to set the access
specifier as private.
• All other classes and functions can access public elements.
• Private elements cannot be accessed outside the class in which
they are declared.
• Private elements can be accessed outside the class in which they
are declared only when the class is a friend class or function is a
friend function of that class.
Conclusion
• Protected elements can be accessed by derived classes. They
are almost similar to the private access specifier.
• If we do not mention any access specifier for the members
inside the class, then by default, the Access Specifier in C++ for
the members will be Private.
• All functions are accessible to the friend function of the class.
Access Specifier Same Class Outside Class Derived Class
Public Modifier YES YES YES
Private Modifier YES NO NO
Protected Modifier YES NO YES
SESSION-07
UML Diagrams Introduction – Use Case Diagram, Class Diagrams
Dr.M.Sivakumar, AP/NWC 109
UML Diagrams Introduction
• UML, or Unified Modeling Language, is a standardized
modeling language used in software engineering for
visualizing, specifying, constructing, and documenting
software systems.
• There are several types of UML diagrams, each serving a
specific purpose in the software development process.
110
Dr.M.Sivakumar, AP/NWC
Why we use UML?
• Use graphical notation: more clearly than natural language
(imprecise) and code (too detailed).
• Help acquire an overall view of a system.
• UML is not dependent on any one language or technology.
• UML moves us from fragmentation to standardization.
111
Dr.M.Sivakumar, AP/NWC
Types of UML Diagrams
• Use case Diagrams
– Describe the functional behavior of the system as seen by the user.
• Class diagrams
– Describe the static structure of the system: Objects, Attributes,
Associations
• Sequence diagrams
– Describe the dynamic behavior between actors and the system and
between objects of the system
• Statechart diagrams
– Describe the dynamic behavior of an individual object (essentially a
finite state automaton)
• Activity Diagrams
– Model the dynamic behavior of a system, in particular the workflow
(essentially a flowchart)
112
Dr.M.Sivakumar, AP/NWC
Use Case Diagram
113
Dr.M.Sivakumar, AP/NWC
Use Case Diagram
114
Dr.M.Sivakumar, AP/NWC
Class Diagram
• It is the most common diagram type for software documentation
• Class diagrams contain classes with their attributes (data members) and
their behaviours (member functions)
• A class is a rectangle divided into three parts
– Class name
– Class attributes (i.e. data members, variables)
– Class operations (i.e. methods)
• The relation between different classes makes up a class diagram
• Modifiers
– Private: -
– Public: +
– Protected: #
– Static: Underlined
(i.e. shared among all members
of the class)
115
Dr.M.Sivakumar, AP/NWC
ClassName
Attributes
Behaviours
+getName() : string
+setName()
-calcInternalStuff(in x : byte, in y : decimal)
-Name : string
+ID : long
#Salary : double
Employee
Class Diagram
• It is the most common diagram type for software documentation
• Class diagrams contain classes with their attributes (data members) and their
behaviours (member functions)
• A class is a rectangle divided into three parts
– Class name
– Class attributes (i.e. data members, variables)
– Class operations (i.e. methods)
• The relation between different classes makes up
a class diagram
116
Dr.M.Sivakumar, AP/NWC
ClassName
Attributes
Behaviours
+getName() : string
+setName()
-calcInternalStuff(in x : byte, in y : decimal)
-Name : string
+ID : long
#Salary : double
Employee
Class Diagram Example
117
Dr.M.Sivakumar, AP/NWC
Account_Name
- Customer_Name
- Balance
+addFunds( )
+withDraw( )
+transfer( )
Name
Attributes
Operations
Class Diagram Example
118
Dr.M.Sivakumar, AP/NWC
Basic components of a class diagram
119
Dr.M.Sivakumar, AP/NWC
The standard class diagram is composed of three sections:
• Upper section: Contains the name of the class. This section is
always required, to know whether it represents the classifier or
an object.
• Middle section: Contains the attributes of the class. Use this
section to describe the qualities of the class. This is only required
when describing a specific instance of a class.
• Bottom section: Includes class operations (methods). Displayed in
list format, each operation takes up its own line. The operations
describe how a class interacts with data.
Class Name
Attributes
Behaviors
RULES TO BE FOLLOWED
120
Dr.M.Sivakumar, AP/NWC
• Class name must be unique to its enclosing namespace.
• The class name begins in uppercase and the space between
multiple words is omitted.
• The first letter of the attribute and operation names is lowercase
with subsequent words starting in uppercase and spaces are
omitted.
• Since the class is the namespace for its attributes and operations
an attribute name must be unambiguous in the context of the class.
Attributes : Second Section
121
Dr.M.Sivakumar, AP/NWC
• How would you identify each instance of that class, i.e., a specific animal?
• Using Attributes
• What are Attributes?
• A significant piece of data containing values that describe each instance of that class
• They are also known as fields, variables or properties
• Format for specifying an attribute:
visibility attributeName : Type [multiplicity] = DefaultValue {property string}
• Visibility: It sets the accessibility of an attribute / method
• Private (-) Visible only to the elements within the same class
• Public (+) Visible to any element that can see the class
• Protected (#) Visible to the elements in the class and its sub class
• Package (~) Visible to elements within the same package
Methods : Third section
122
Dr.M.Sivakumar, AP/NWC
• They are also known as operations or functions
• It specifies the behaviour of a class
• Eg: We may want to change the name of an Animal
• We could add a method setName
• We could also create a method for eating, since all of our animals eat
• Lets take another example : Employee Details
Relationships
123
Dr.M.Sivakumar, AP/NWC
Relationships
• Association: Represents a relationship between two classes, indicating that
objects of one class are connected to objects of another class.
• Inheritance/Generalization: Represents an "is-a" relationship, where one class
(subclass) inherits attributes and operations from another class (superclass). It is
depicted with a solid line and an arrowhead pointing to the superclass.
• Dependencies: Indicates that one class depends on another class, typically in
terms of method parameters or return types. Dependencies are represented with
a dashed arrow.
• Aggregation: Represents a "whole-part" relationship, where one class is
composed of one or more instances of another class. It is depicted with a hollow
diamond at the aggregate end.
• Composition: Similar to aggregation but with stronger ownership semantics. It
indicates that the "part" class is entirely dependent on the "whole" class and has
no independent existence. Composition is denoted with a filled diamond at the
composite end.
• Multiplicity: Specifies how many instances of one class are related to instances of
another class. It is denoted using numbers or ranges.
Dr.M.Sivakumar, AP/NWC 124
SESSION-08
Dr.M.Sivakumar, AP/NWC 125
Practice questions
• Define a class BankAccount with attributes such as account
number, account holder name, and balance. Implement methods
to deposit money, withdraw money, and display account
information.
• Create a class Student with attributes like roll number, name,
marks in different subjects, etc. Implement methods to calculate
total marks, average marks, and display student information.
• Define a class vehicle with attributes like the vehicle's registration
number, make, model, year of manufacture, and current mileage.
Implement methods for setting and getting these attributes
• Define a book and contain attributes such as title, author, ISBN,
genre, and availability status. It should have methods for setting
and getting these attributes.
Dr.M.Sivakumar, AP/NWC 126
SESSION-09
Dr.M.Sivakumar, AP/NWC 127
Quiz/Puzzles/Review
Questions
Dr.M.Sivakumar, AP/NWC 128
END
129
Dr.M.Sivakumar, AP/NWC

More Related Content

PDF
Pre-Project Software Quality Assurance Components.pdf
PDF
Mitsubishi plc fxfamilycatalogverf-160517025323 dienhathe.vn
PPTX
Software Engineering
PPTX
Recorder and pen drive system and display method
PDF
SDN-ppt-new
PPT
Pass Transistor Logic
PDF
Plc ppt
PPTX
Robot programming
Pre-Project Software Quality Assurance Components.pdf
Mitsubishi plc fxfamilycatalogverf-160517025323 dienhathe.vn
Software Engineering
Recorder and pen drive system and display method
SDN-ppt-new
Pass Transistor Logic
Plc ppt
Robot programming

What's hot (20)

PPT
PLC Basic
PPT
design metrics for embedded systems and rtos
PDF
Waterfall model
PPTX
PPT
debugging (1).ppt
PPTX
Compiler an overview
PDF
Automation
PPTX
Testing strategies
PDF
Deadlock Avoidance - OS
PPTX
PDF
Unit I OS.pdf
PPT
Chapter 2 ladder
PPT
VLSI- Unit I
PPTX
Advances in Verification - Workshop at BMS College of Engineering
PPT
Inter-Process communication in Operating System.ppt
PPTX
Basic concept of process
PPTX
Demand paging
PPTX
Multimedia synchronization
PPTX
What is Ad-Hoc Testing
PPTX
UART Communication
PLC Basic
design metrics for embedded systems and rtos
Waterfall model
debugging (1).ppt
Compiler an overview
Automation
Testing strategies
Deadlock Avoidance - OS
Unit I OS.pdf
Chapter 2 ladder
VLSI- Unit I
Advances in Verification - Workshop at BMS College of Engineering
Inter-Process communication in Operating System.ppt
Basic concept of process
Demand paging
Multimedia synchronization
What is Ad-Hoc Testing
UART Communication
Ad

Similar to Object Oriented Design and Programming Unit-01 (20)

PPTX
Unit - I Intro. to OOP Concepts and Control Structure -OOP and CG (2024 Patte...
PPT
Unit 1- Basic concept of object-oriented-programming.ppt
PPT
Introduction to oop
PPT
Share Unit 1- Basic concept of object-oriented-programming.ppt
PDF
6_Object-oriented-using-java.pdf object oriented programming concepts
PDF
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
PPT
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
PPT
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
PPTX
DOC-20210303-WA0017..pptx,coding stuff in c
PPTX
OOP-1.pptx
PDF
C++ Programming with examples for B.Tech
PPTX
SE-IT JAVA LAB OOP CONCEPT
PPSX
DITEC - Software Engineering
PPTX
OOPsConceptspythonenineeringcomputerscienceand engineering.pptx
PPTX
PCC-202-COM -OOP and CG (2024 Pattern).pptx
PPTX
Principles of OOPs.pptx
PPTX
Need of object oriented programming
PPTX
1 unit (oops)
PPT
1-Lec - Introduction vhvv,vbvv,v (2).ppt
Unit - I Intro. to OOP Concepts and Control Structure -OOP and CG (2024 Patte...
Unit 1- Basic concept of object-oriented-programming.ppt
Introduction to oop
Share Unit 1- Basic concept of object-oriented-programming.ppt
6_Object-oriented-using-java.pdf object oriented programming concepts
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
DOC-20210303-WA0017..pptx,coding stuff in c
OOP-1.pptx
C++ Programming with examples for B.Tech
SE-IT JAVA LAB OOP CONCEPT
DITEC - Software Engineering
OOPsConceptspythonenineeringcomputerscienceand engineering.pptx
PCC-202-COM -OOP and CG (2024 Pattern).pptx
Principles of OOPs.pptx
Need of object oriented programming
1 unit (oops)
1-Lec - Introduction vhvv,vbvv,v (2).ppt
Ad

More from Sivakumar M (12)

PPTX
Introduction to Operating Systems and its basics
PPTX
Operating Systems Process Management.pptx
PPTX
Operating Systems Protection and Security
PPTX
Operating Systems CPU Scheduling and its Algorithms
PPTX
18CSC311J WEB DESIGN AND DEVELOPMENT UNIT-4
PPTX
18CSC311J WEB DESIGN AND DEVELOPMENT UNIT-2
PPTX
18CSC311J WEB DESIGN AND DEVELPMENT UNIT-1
PPTX
18CSC311J Web Design and Development UNIT-3
PPTX
Object Oriented Design and Programming Unit-05
PPTX
Object Oriented Design and Programming Unit-04
PPTX
Object Oriented Design and Programming Unit-03
PPTX
Object Oriented Design and Programming Unit-02
Introduction to Operating Systems and its basics
Operating Systems Process Management.pptx
Operating Systems Protection and Security
Operating Systems CPU Scheduling and its Algorithms
18CSC311J WEB DESIGN AND DEVELOPMENT UNIT-4
18CSC311J WEB DESIGN AND DEVELOPMENT UNIT-2
18CSC311J WEB DESIGN AND DEVELPMENT UNIT-1
18CSC311J Web Design and Development UNIT-3
Object Oriented Design and Programming Unit-05
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-02

Recently uploaded (20)

PPTX
Geodesy 1.pptx...............................................
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
composite construction of structures.pdf
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
web development for engineering and engineering
PDF
PPT on Performance Review to get promotions
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
Lecture Notes Electrical Wiring System Components
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
Geodesy 1.pptx...............................................
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
composite construction of structures.pdf
Internet of Things (IOT) - A guide to understanding
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Model Code of Practice - Construction Work - 21102022 .pdf
Embodied AI: Ushering in the Next Era of Intelligent Systems
web development for engineering and engineering
PPT on Performance Review to get promotions
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Lecture Notes Electrical Wiring System Components
R24 SURVEYING LAB MANUAL for civil enggi
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf

Object Oriented Design and Programming Unit-01

  • 1. 21CSC101T OBJECT ORIENTED DESIGN AND PROGRAMMING Unit-1 - Introduction to OOPS 1 Dr.M.Sivakumar, AP/NWC
  • 2. Course Outcomes (CO) At the end of this course, learners will be able to: • CO-1: Create programs using object-oriented approach and design methodologies • CO-2: Construct programs using method overloading and operator overloading • CO-3: Create programs using inline, friend and virtual functions, construct programs using standard templates • CO-4: Construct programs using exceptional handling and collections • CO-5: Create Models of the system using UML Diagrams 2 Dr.M.Sivakumar, AP/NWC
  • 3. Unit-1 - Introduction to OOPS 1. Object-Oriented Programming - Features of C++ 2. I/O Operations, Data Types, Variables-Static, Constants, Pointers 3. Type Conversions - Conditional and looping statements 4. Arrays - C++ 11 features 5. Class and Objects, Abstraction and Encapsulation, 6. Access Specifiers, Methods 7. UML Diagrams Introduction - Use Case Diagram, Class Diagram. 8. Practice questions from elab 9. Quiz/Puzzles/Review Questions 3 Dr.M.Sivakumar, AP/NWC
  • 4. SESSION-01 Introduction to Object-Oriented Programming, Features of C++ Dr.M.Sivakumar, AP/NWC 4
  • 6. Programming Languages • Programming a computer involves writing instructions that enable a computer to carry out a single task or a group of tasks • Writing these sets of instructions, which are known as programs or software, requires using a computer programming language and resolving any errors in the instructions so that the programs work correctly • Programs are also frequently called application programs • Simply applications, because you apply them to a task such as preparing payroll checks, creating inventory reports, or—as in the case of game programs—even entertaining someone 6 Dr.M.Sivakumar, AP/NWC
  • 7. Programming Languages • learning a computer programming language requires learning both vocabulary and syntax. • The rules of any language make up its syntax. • When you write programs, you write program statements that are instructions that are similar to English-language sentences. 7 Dr.M.Sivakumar, AP/NWC
  • 8. Types of Programming Languages • Machine level Language • Assembly level Language • High level Language –Procedure oriented programming(POP) language –Object oriented programming(OOP) language. 8 Dr.M.Sivakumar, AP/NWC
  • 9. Procedure Oriented Programming Language • Drawbacks – Global data access – It does not model real word problem very well – No data hiding 9 Dr.M.Sivakumar, AP/NWC
  • 10. Characteristics of procedure oriented programming • Emphasis is on doing things(algorithm) • Large programs are divided into smaller programs known as functions • Most of the functions share global data • Data move openly around the system from function to function • Function transforms data from one form to another • Employs top-down approach in program design 10 Dr.M.Sivakumar, AP/NWC
  • 11. Object Oriented Programming • Object oriented programming as an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand 11 Dr.M.Sivakumar, AP/NWC
  • 14. Object Oriented Programming • Combine data and functions into object. (Member Data & Member Functions) • Member functions are also called methods. • Member data are hidden within member functions. • Data Encapsulation & Data Hiding. • Objects interact by sending messages to each other. 14 Dr.M.Sivakumar, AP/NWC
  • 15. Object Oriented Programming Vs Procedural Oriented Programming Procedure Oriented Programming Object Oriented Programming program is divided into small parts called functions program is divided into parts called objects. Importance is not given to data but to functions as well as sequence of actions to be done. Importance is given to the data rather than procedures or functions because it works as a real world. follows Top Down approach OOP follows Bottom Up approach. It does not have any access specifier OOP has access specifiers named Public, Private, Protected, etc Data can move freely from function to function in the system objects can move and communicate with each other through member functions. It does not have any proper way for hiding data so it is less secure OOP provides Data Hiding so provides more security Overloading is not possible In OOP, overloading is possible in the form of Function Overloading and Operator Overloading. 15 Dr.M.Sivakumar, AP/NWC
  • 16. Basic concepts of OOPS 1. Objects 2. Classes 3. Data abstraction and encapsulation 4. Inheritance 5. Polymorphism 6. Dynamic binding 7. Message passing 16 Dr.M.Sivakumar, AP/NWC
  • 17. Objects • Software objects model real-world objects or abstract concepts. dog, bicycle, queue • Real-world objects have states and behaviors. Dogs' states: name, color, breed, hungry Dogs' behaviors: barking, fetching • How do software objects implement real-world objects? Use variables/data to implement states. Use methods/functions to implement behaviors. • An object is a software bundle of variables and related methods. 17 Dr.M.Sivakumar, AP/NWC
  • 18. Class • A class is a blueprint or prototype defining the variables and methods common to all objects of a certain kind. • An object is an instance of a certain class. • After you have created a class, you must create an instance of it before you can use. • Class variables and class methods. 18 Dr.M.Sivakumar, AP/NWC
  • 22. Data abstraction and encapsulation • It is a mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse 22 Dr.M.Sivakumar, AP/NWC
  • 23. Data abstraction and encapsulation 23 Dr.M.Sivakumar, AP/NWC
  • 24. Data abstraction and encapsulation • Encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper • Access to the code and data inside the wrapper is tightly controlled through a well-defined interface 24 Dr.M.Sivakumar, AP/NWC
  • 25. Inheritance • Inheritance is the process by which one object acquires the properties of another object 25 Dr.M.Sivakumar, AP/NWC
  • 28. Polymorphism • Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions • The specific action is determined by the exact nature of the situation 28 Dr.M.Sivakumar, AP/NWC
  • 31. Message Passing  What are Messages?  Software objects interact and communicate with each other by sending messages to each other. 31 Dr.M.Sivakumar, AP/NWC
  • 32. Benefits of Object-Oriented programming • Reuse of existing code • Improved maintainability • Often a ‘natural’ way to describe a system 32 Dr.M.Sivakumar, AP/NWC
  • 33. Applications of Object Oriented Programming • Client-Server Systems • Real-Time System • Object-Oriented Databases • Simulation and modelling • AI and expert systems • Neural networks and parallel programming 33 Dr.M.Sivakumar, AP/NWC
  • 35. Introduction to C++ • C++ is a general-purpose programming language that was developed as an extension of the C programming language with object-oriented programming features • C++ was invented by Bjarne Stroustrup in 1979, at Bell Laboratories in Murray Hill, New Jersey • C++ is derived from the C language • C++ provides a combination of low-level features for systems programming and high-level features for application development. • C++ is also the language from which both Java and C# are derived 35 Dr.M.Sivakumar, AP/NWC
  • 37. Features of C++ • Object-Oriented Programming (OOP) • Procedural Programming • Standard Template Library (STL) • Memory Management • Performance • Portability with relatively few modifications • Wide Usage 37 Dr.M.Sivakumar, AP/NWC
  • 38. Difference between C and C++ C C++ Procedural programming language Supports both procedural programming (like C) and object-oriented programming (OOP) Simpler syntax Extends the syntax of C by adding new keywords and features Memory management is typically done manually using functions like malloc and free operators like new and delete for dynamic memory allocation. Does not have a standard template library Includes the Standard Template Library (STL) Does not support function overloading Allows function overloading Does not have the concept of namespaces Introduces namespaces printf and scanf for input and output cout for output and cin for input 38 Dr.M.Sivakumar, AP/NWC
  • 39. SESSION-02 I/O Operations, Data Types, Variables -Static, Constants - Pointers Dr.M.Sivakumar, AP/NWC 39
  • 40. I/O OPERATIONS, DATA TYPES, VARIABLES- STATIC, CONSTANTS Dr.M.Sivakumar, AP/NWC 40
  • 41. I/O Operations • C++ I/O operation occurs in streams, which involve transfer of information into byte • It’s a sequences of bytes • Stream involved in two ways • It is the source as well as the destination of data • C++ programs input data and output data from a stream. • Streams are related with a physical device such as the monitor or with a file stored on the secondary memory. • In a text stream, the sequence of characters is divided into lines, with each line being terminated. • With a new-line character (n) . On the other hand, a binary stream contains data values using their memory representation. 41 Dr.M.Sivakumar, AP/NWC
  • 42. I/O Operations 42 Dr.M.Sivakumar, AP/NWC Stream in C Text Stream Binary Stream
  • 43. Cascading of Input or Output Operators 43 Dr.M.Sivakumar, AP/NWC • << operator –It can use multiple times in the same line. • Its called Cascading • Cout ,Cin can cascaded • For example • cout<<“n Enter the Marks”; • cin>> ComputerNetworks>>OODP;
  • 44. Reading and Writing Characters and Strings 44 Dr.M.Sivakumar, AP/NWC • 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;
  • 45. Formatted Input and Output Operations 45 Dr.M.Sivakumar, AP/NWC Formatted I/O I/O class function and flages Manipulators
  • 46. Example 46 Dr.M.Sivakumar, AP/NWC #include<iostream.h> #define PI 3.14159 main() { cout.precision(3); cout.width(10); cout.fill(‘*’); cout<<PI; } Output *****3.142
  • 47. Formatting with flags 47 Dr.M.Sivakumar, AP/NWC • The setf() is a member function of the ios class that is used to set flags for formatting output. • Syntax: cout.setf(flag, bit-field) • Here, flag defined in the ios class specifies how the output should be formatted • bit-field is a constant (defined in ios ) that identifies the group to which the formatting flag belongs to. • There are two types of setf()—one that takes both flag and bit- fields and the other that takes only the flag .
  • 49. Formatting Output Using Manipulators 49 Dr.M.Sivakumar, AP/NWC
  • 50. Data Types in C++ 50 Dr.M.Sivakumar, AP/NWC
  • 51. Variables 51 Dr.M.Sivakumar, AP/NWC 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. Static Variables Local Variables Instance variables 01 02 03 Constant Variables 04
  • 52. Variables 52 Dr.M.Sivakumar, AP/NWC Local Variables Instance Variables Static Variables Constant Variables Local variable: These are the variables which are declared within the method of a class. Example: public class Car { public: // Method void display(int m) { // Created a local variable int model=m; cout<<model; } }; Static variables: Static variables are also called as class variables. These variables have only one copy that is shared by all the different objects in a class. Example: class Car { public: //Static variable static int tyres; void init() { tyres=4; } }; Instance variable: These are the variables which are declared in a class but outside a method, constructor or any block. Example: public class Car { private: // Created an instance variable String color; Car(String c) { color=c; } }; Constant is something that doesn't change. In C language and C++ we use the keyword const to make program elements constant. Example: const int i = 10; void f(const int i); class Test { const int i; };
  • 53. CONSTANTS • Constants are identifiers whose value does not change. While variables can change their value at any time, constants can never change their value. • Constants are used to define fixed values such as Pi or the charge on an electron so that their value does not get changed in the program even by mistake. • A constant is an explicit data value specified by the programmer. • The value of the constant is known to the compiler at the compile time. Dr.M.Sivakumar, AP/NWC 53
  • 54. Declaring Constants • Rule 1 Constant names are usually written in capital letters to visually distinguish them from other variable names which are normally written in lower case characters. • Rule 2 No blank spaces are permitted in between the # symbol and define keyword. • Rule 3 Blank space must be used between #define and constant name and between constant name and constant value. • Rule 4 #define is a preprocessor compiler directive and not a statement. Therefore, it does not end with a semi-colon. Dr.M.Sivakumar, AP/NWC 54
  • 55. Operators • Arithmetic Operators • Relational Operators • Logical Operators • Bitwise Operators • Assignment Operators • Misc Operators Dr.M.Sivakumar, AP/NWC 55
  • 56. Arithmetic Operators Operator Description Example + Adds two operands A + B will give 30 - Subtracts second operand from the first A - B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by de-numerator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0 ++ Increment operator, increases integer value by one A++ will give 11 -- Decrement operator, decreases integer value by one A-- will give 9 Dr.M.Sivakumar, AP/NWC 56
  • 57. Relational Operators Operator Description Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. Dr.M.Sivakumar, AP/NWC 57
  • 58. Logical Operators Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true. Dr.M.Sivakumar, AP/NWC 58
  • 59. Bitwise Operators Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111 Dr.M.Sivakumar, AP/NWC 59
  • 60. Assignment Operators Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C - A *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand. C *= A is equivalent to C = C * A /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand. C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand. C %= A is equivalent to C = C % A Dr.M.Sivakumar, AP/NWC 60
  • 61. Misc Operators Operator Description Example sizeof() sizeof operator returns the size of a variable. sizeof(a), where ‘a’ is integer, and will return 4. ? : Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of Y. , Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list. . and -> Member operators are used to reference individual members of classes, structures, and unions. Cast Casting operators convert one data type to another. int(2.2000) would return 2. & Pointer operator & returns the address of a variable. &a; will give actual address of the variable. * Pointer operator is pointer to a variable. *var; will pointer to a variable var. Dr.M.Sivakumar, AP/NWC 61
  • 62. Operators Precedence in C++ Dr.M.Sivakumar, AP/NWC 62 Category Operator Associativity Postfix () [] -> . ++ - - Left to right Unary + - ! ~ ++ - - (type)* & sizeof Right to left Multiplicative * / % Left to right Additive + - Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left Comma , Left to right
  • 63. Special Operators Dr.M.Sivakumar, AP/NWC 63 1 2 3 4 In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by using scope resolution operator (::), because this operator allows access to the global version of a variable. 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 pointer variable. Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided delete operator by C++ language. 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. Scope resolution operator new Operator delete Operator Member Operator
  • 64. Pointers • Pointers are symbolic representation of addresses. • They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. • Syntax data_type *pointer_variable; • Example int *p,sum; Assignment • integer type pointer can hold the address of another int variable • To assign the address of variable to pointer-ampersand symbol (&) p=&sum; this pointer hold the adderss of current object int num; this->num=num; 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. 64 Dr.M.Sivakumar, AP/NWC
  • 65. Pointers int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch // pointer to character Steps: (a) We define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the address available in the pointer variable. 65 Dr.M.Sivakumar, AP/NWC
  • 67. How to use it #include <iostream> using namespace std; int main () { int var = 20; // actual variable declaration. int *ip; // pointer variable ip = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; return 0; } 67 Dr.M.Sivakumar, AP/NWC Output: Value of var variable: 20 Address stored in ip variable: 0xbfc601ac Value of *ip variable: 20
  • 68. Pointers and Arrays #include <iostream> using namespace std; int main() { //Pointer declaration int *p; //Array declaration int arr[]={1, 2, 3, 4, 5, 6}; //Assignment p = arr; for(int i=0; i<6;i++) { cout<<*p<<endl; //++ moves the pointer to next int position p++; } return 0; } 68 Dr.M.Sivakumar, AP/NWC OUTPUT: 0 1 2 3 4 5 6
  • 69. this Pointers • this pointer hold the address of current object • int num; • This->num=num; 69 Dr.M.Sivakumar, AP/NWC
  • 70. this Pointers Example #include <iostream> using namespace std; class Employee { int id; //data member (also instance variable) char name[20]; //data member(also instance variable) float salary; public: Employee(int id, string name, float salary) { this->id = id; this->name = name; this->salary = salary; } void display() { cout<<id<<" "<<name<<" "<<salary<<endl; } }; 70 Dr.M.Sivakumar, AP/NWC 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; } Output: 101 Sonoo 890000 102 Nakul 59000
  • 71. Function using pointers 71 Dr.M.Sivakumar, AP/NWC #include<iostream> using namespace std; void swap(int *a ,int *b ); //Call By Reference int main() { int p,q; cout<<"nEnter Two Number You Want To Swap n"; cin>>p>>q; swap(&p,&q); cout<<"nAfter Swapping Numbers Are Given belownn"; cout<<p<<" "<<q<<" n"; return 0; } void swap(int *a,int *b) { int c; c=*a; *a=*b; *b=c; } Output: Enter Two Number You Want to Swap 10 20 After Swapping Numbers Are Given below 20 10
  • 72. MCQ 72 Dr.M.Sivakumar, AP/NWC What will happen in the following C++ code snippet? 1)Int a=100, b=200; 2) Int *p=&a, *q=&b; 3) p=q; Choose the correct one. a) b is assigned to a b) p now points to b c) a is assigned to b d) q now points to a
  • 73. MCQ 73 Dr.M.Sivakumar, AP/NWC a) b is assigned to a b) p now points to b c) a is assigned to b d) q now points to a
  • 74. MCQ 74 Dr.M.Sivakumar, AP/NWC 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); }
  • 75. MCQ 75 Dr.M.Sivakumar, AP/NWC 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.
  • 76. SESSION-03 Type Conversions, Conditional and Looping Statements Dr.M.Sivakumar, AP/NWC 76
  • 77. Type Conversions • Type conversion is the process that converts the predefined data type of one variable into an appropriate data type. • Type conversion can be done in two ways in C++ 1. Implicit type conversion 2. Explicit type conversion 77 Dr.M.Sivakumar, AP/NWC
  • 78. Implicit Type Conversions • The type conversion that is done automatically done by the compiler • This type of conversion is also known as automatic conversion #include <iostream> using namespace std; int main () { // assign the integer value int num1 = 25; // declare a float variable float num2; // convert int value into float variable using implicit conversion num2 = num1; cout << " The value of num1 is: " << num1 << endl; cout << " The value of num2 is: " << num2 << endl; return 0; } 78 Dr.M.Sivakumar, AP/NWC Output: The value of num1 is: 25 The value of num2 is: 25
  • 79. Explicit Type Conversions (or) Type Casting • Conversions that require user intervention to change the data type of one variable to another • Hence, it is also known as typecasting • The explicit type conversion is done in two ways: – Explicit conversion using the cast operator – Explicit conversion using the assignment operator Dr.M.Sivakumar, AP/NWC 79
  • 80. 1. Explicit conversion using the cast operator #include <iostream> using namespace std; int main () { float f2 = 6.7; // use cast operator to convert data from one type to another int x = static_cast <int> (f2); cout << " The value of x is: " << x; return 0; } Dr.M.Sivakumar, AP/NWC 80
  • 81. 2. Explicit conversion using the assignment operator #include <iostream> using namespace std; int main () { // declare a float variable float num2; // initialize an int variable int num1 = 25; // convert data type from int to float num2 = (float) num1; cout << " The value of int num1 is: " << num1 << endl; cout << " The value of float num2 is: " << num2 << endl; return 0; } Dr.M.Sivakumar, AP/NWC 81
  • 82. Conditional and looping statements • if…else • switch • for • while • do…while • break • continue 82 Dr.M.Sivakumar, AP/NWC
  • 83. SESSION-04 Arrays - C++ 11 features Dr.M.Sivakumar, AP/NWC 83
  • 84. Arrays • Declaring Arrays type arrayName [ arraySize ]; • Initializing Arrays double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0}; balance[4] = 50.0; • Accessing Array Elements 84 Dr.M.Sivakumar, AP/NWC
  • 85. Accessing Array Elements #include <iostream> using namespace std; #include <iomanip> using std::setw; int main () { int n[ 10 ]; // n is an array of 10 integers // initialize elements of array n to 0 for ( int i = 0; i < 10; i++ ) { n[ i ] = i + 100; // set element at location i to i + 100 } cout << "Element" << setw( 13 ) << "Value" << endl; // output each array element's value for ( int j = 0; j < 10; j++ ) { cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl; } return 0; } 85 Dr.M.Sivakumar, AP/NWC Element Value 0 100 1 101 2 102 3 103 4 104 5 105 6 106 7 107 8 108 9 109
  • 86. C++ version 11 features • Simple and User Friendly • Object Oriented Programming • Platform Dependent • Structured Programming Language • Mid-Level Programming Language • Rich Library • Case-Sensitive • Dynamic Memory Allocation • Memory Management • Powerful and Fast 86 Dr.M.Sivakumar, AP/NWC
  • 87. SESSION-05 Class and Objects, Abstraction and Encapsulation Dr.M.Sivakumar, AP/NWC 87
  • 88. CLASS AND OBJECTS, ABSTRACTION AND ENCAPSULATION 88 Dr.M.Sivakumar, AP/NWC
  • 89. Class • Class is a user defined data type, defined using keywork class. • It holds its own data members and member functions, • It can be accessed and used by creating instance of that class. • The variables inside class definition are called as data members and the functions are called member functions class className { data members member functions }; Dr.M.Sivakumar, AP/NWC 89
  • 90. Syntax of Class class ClassName { public: // Member variables (attributes) dataType memberVariable1; dataType memberVariable2; // ... // Member functions (methods) returnType methodName1(ParameterType1 parameter1, ParameterType2 parameter2) { // Function body } returnType methodName2(ParameterType3 parameter3) { // Function body } // ... }; 90 Dr.M.Sivakumar, AP/NWC
  • 91. Class • Class is just a blue print, which declares and defines characteristics and behavior, namely data members and member functions respectively. • All objects of this class will share these characteristics and behavior. • Class name must start with an uppercase letter(Although this is not mandatory). Example, class Student 91 Dr.M.Sivakumar, AP/NWC Example class Room { public: double length; double breadth; double height; double calculateArea() { return length * breadth; } double calculateVolume() { return length * breadth * height; } };
  • 93. Data Member 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 • static data member Acts as a global variable Dr.M.Sivakumar, AP/NWC 93
  • 94. Static Data Member • Static data member is declared using the static keyword. • There is only one copy of the static data member in the class. All the objects share the static data member. • The static data member is always initialized to zero when the first class object is created. Syntax: static data_type datamember_name; Here static is the keyword. data_type – int , float etc… datamember_name – user defined Dr.M.Sivakumar, AP/NWC 94
  • 95. Static Data Member #include <iostream> using namespace std; class Account { public: int accno; //data member (also instance variable) string name; static int count; Account(int accno, string name) // Constructor Function { this->accno = accno; this->name = name; count++; } void display() { cout<<accno<<" "<<name<<endl; } }; Dr.M.Sivakumar, AP/NWC 95 int Account::count=0; int main(void) { Account a1 =Account(201, "Sanjay"); //creating an object of Account Account a2=Account(202, "Nakul"); Account a3=Account(203, "Ranjana"); a1.display(); a2.display(); a3.display(); cout<<"Total Objects are: "<<Account::count; return 0; } Output: 201 Sanjay 202 Nakul 203 Ranjana Total Objects are: 3
  • 96. 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 Dr.M.Sivakumar, AP/NWC 96
  • 97. Member Functions Dr.M.Sivakumar, AP/NWC 97 class Rectangle { private: int width, length; public: void set (int w, int l); int area() { return width*length; } }; void Rectangle :: set (int w, int l) { width = w; length = l; } member function keyword Class Name inside the class outside the class class name Member function int main() { Rectangle r2; r1.set(5,8); int x=r1.area(); cout<<"x value in r1 "<<x; r2.set(5,8); int x=r1.area(); cout<<"x value in r2 "<<x; } Object creation Inside the function scope operator
  • 98. 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. Syntax: datatype function_name() const { } Dr.M.Sivakumar, AP/NWC 98
  • 99. const member function #include<iostream> using namespace std; class sample { private: int val; public: sample(int x = 0) { val = x; } int getValue() const { return val; } }; Dr.M.Sivakumar, AP/NWC 99 int main() { const sample s(20); sample s1(2); cout << "The value using object d : " << s.getValue(); cout << "nThe value using object d1 : " << s1.getValue(); return 0; }
  • 101. Access Specifiers • One of the main features of object-oriented programming languages such as C++ is data hiding. • Data hiding refers to restricting access to data members of a class. • This is to prevent other functions and classes from tampering with the class data. Definition : The access specifiers of C++ allows us to determine which class members are accessible to other classes and functions, and which are not.
  • 102. Types of access specifiers • Public members can be accessed from anywhere in the program, including outside the class. Public • Private members can only be accessed from within the class itself. Private • Protected members can be accessed from within the class itself, from derived classes and from friend function Protected
  • 103. Example: public #include<iostream> using namespace std; class student { public: char name[20]; int age; void display(); }; int main() { student s1; cout<<"Enter name:"; cin>>s1.name; cout<<"Enter age:"; cin>>s1.age; s1.display(); return 0; } void student::display() { cout<<"Name:"<<name<<endl; cout<<"Age:"<<age; } Output: Enter name:raja Enter age:20 Name:raja Age:20
  • 104. Example: private #include<iostream> using namespace std; class student { private: char name[20]; int age; public: void getdata(); void display(); }; int main() { student s1; //cin>>s1.name; //cin>>s1.age; s1.getdata(); s1.display(); return 0; } void student::getdata() { cout<<"Enter name:"; cin>>name; cout<<"Enter age:"; cin>>age; } void student::display() { cout<<"Name:"<<name<<endl; cout<<"Age:"<<age; } Output: Enter name:raja Enter age:21 Name:raja Age:21
  • 105. Example: protected #include<iostream> using namespace std; class person { protected: char name[20]; int age; }; class student: public person { public: void getdata(); void display(); }; int main() { student s1; s1.getdata(); s1.display(); return 0; } void student::getdata() { cout<<"Enter name:"; cin>>name; cout<<"Enter age:"; cin>>age; } void student::display() { cout<<"Name:"<<name<<endl; cout<<"Age:"<<age; } Output: Enter name:raja Enter age:22 Name:raja Age:22
  • 106. Syntax of Declaring Access Specifiers in C++ class ClassName { private: // declare private members/methods here public: // declare public members/methods here protected: // declare protected members/methods here };
  • 107. Conclusion • If any sensitive information that, when leaked or tampered with, can cause trouble, always make sure to set the access specifier as private. • All other classes and functions can access public elements. • Private elements cannot be accessed outside the class in which they are declared. • Private elements can be accessed outside the class in which they are declared only when the class is a friend class or function is a friend function of that class.
  • 108. Conclusion • Protected elements can be accessed by derived classes. They are almost similar to the private access specifier. • If we do not mention any access specifier for the members inside the class, then by default, the Access Specifier in C++ for the members will be Private. • All functions are accessible to the friend function of the class. Access Specifier Same Class Outside Class Derived Class Public Modifier YES YES YES Private Modifier YES NO NO Protected Modifier YES NO YES
  • 109. SESSION-07 UML Diagrams Introduction – Use Case Diagram, Class Diagrams Dr.M.Sivakumar, AP/NWC 109
  • 110. UML Diagrams Introduction • UML, or Unified Modeling Language, is a standardized modeling language used in software engineering for visualizing, specifying, constructing, and documenting software systems. • There are several types of UML diagrams, each serving a specific purpose in the software development process. 110 Dr.M.Sivakumar, AP/NWC
  • 111. Why we use UML? • Use graphical notation: more clearly than natural language (imprecise) and code (too detailed). • Help acquire an overall view of a system. • UML is not dependent on any one language or technology. • UML moves us from fragmentation to standardization. 111 Dr.M.Sivakumar, AP/NWC
  • 112. Types of UML Diagrams • Use case Diagrams – Describe the functional behavior of the system as seen by the user. • Class diagrams – Describe the static structure of the system: Objects, Attributes, Associations • Sequence diagrams – Describe the dynamic behavior between actors and the system and between objects of the system • Statechart diagrams – Describe the dynamic behavior of an individual object (essentially a finite state automaton) • Activity Diagrams – Model the dynamic behavior of a system, in particular the workflow (essentially a flowchart) 112 Dr.M.Sivakumar, AP/NWC
  • 115. Class Diagram • It is the most common diagram type for software documentation • Class diagrams contain classes with their attributes (data members) and their behaviours (member functions) • A class is a rectangle divided into three parts – Class name – Class attributes (i.e. data members, variables) – Class operations (i.e. methods) • The relation between different classes makes up a class diagram • Modifiers – Private: - – Public: + – Protected: # – Static: Underlined (i.e. shared among all members of the class) 115 Dr.M.Sivakumar, AP/NWC ClassName Attributes Behaviours +getName() : string +setName() -calcInternalStuff(in x : byte, in y : decimal) -Name : string +ID : long #Salary : double Employee
  • 116. Class Diagram • It is the most common diagram type for software documentation • Class diagrams contain classes with their attributes (data members) and their behaviours (member functions) • A class is a rectangle divided into three parts – Class name – Class attributes (i.e. data members, variables) – Class operations (i.e. methods) • The relation between different classes makes up a class diagram 116 Dr.M.Sivakumar, AP/NWC ClassName Attributes Behaviours +getName() : string +setName() -calcInternalStuff(in x : byte, in y : decimal) -Name : string +ID : long #Salary : double Employee
  • 117. Class Diagram Example 117 Dr.M.Sivakumar, AP/NWC Account_Name - Customer_Name - Balance +addFunds( ) +withDraw( ) +transfer( ) Name Attributes Operations
  • 119. Basic components of a class diagram 119 Dr.M.Sivakumar, AP/NWC The standard class diagram is composed of three sections: • Upper section: Contains the name of the class. This section is always required, to know whether it represents the classifier or an object. • Middle section: Contains the attributes of the class. Use this section to describe the qualities of the class. This is only required when describing a specific instance of a class. • Bottom section: Includes class operations (methods). Displayed in list format, each operation takes up its own line. The operations describe how a class interacts with data. Class Name Attributes Behaviors
  • 120. RULES TO BE FOLLOWED 120 Dr.M.Sivakumar, AP/NWC • Class name must be unique to its enclosing namespace. • The class name begins in uppercase and the space between multiple words is omitted. • The first letter of the attribute and operation names is lowercase with subsequent words starting in uppercase and spaces are omitted. • Since the class is the namespace for its attributes and operations an attribute name must be unambiguous in the context of the class.
  • 121. Attributes : Second Section 121 Dr.M.Sivakumar, AP/NWC • How would you identify each instance of that class, i.e., a specific animal? • Using Attributes • What are Attributes? • A significant piece of data containing values that describe each instance of that class • They are also known as fields, variables or properties • Format for specifying an attribute: visibility attributeName : Type [multiplicity] = DefaultValue {property string} • Visibility: It sets the accessibility of an attribute / method • Private (-) Visible only to the elements within the same class • Public (+) Visible to any element that can see the class • Protected (#) Visible to the elements in the class and its sub class • Package (~) Visible to elements within the same package
  • 122. Methods : Third section 122 Dr.M.Sivakumar, AP/NWC • They are also known as operations or functions • It specifies the behaviour of a class • Eg: We may want to change the name of an Animal • We could add a method setName • We could also create a method for eating, since all of our animals eat • Lets take another example : Employee Details
  • 124. Relationships • Association: Represents a relationship between two classes, indicating that objects of one class are connected to objects of another class. • Inheritance/Generalization: Represents an "is-a" relationship, where one class (subclass) inherits attributes and operations from another class (superclass). It is depicted with a solid line and an arrowhead pointing to the superclass. • Dependencies: Indicates that one class depends on another class, typically in terms of method parameters or return types. Dependencies are represented with a dashed arrow. • Aggregation: Represents a "whole-part" relationship, where one class is composed of one or more instances of another class. It is depicted with a hollow diamond at the aggregate end. • Composition: Similar to aggregation but with stronger ownership semantics. It indicates that the "part" class is entirely dependent on the "whole" class and has no independent existence. Composition is denoted with a filled diamond at the composite end. • Multiplicity: Specifies how many instances of one class are related to instances of another class. It is denoted using numbers or ranges. Dr.M.Sivakumar, AP/NWC 124
  • 126. Practice questions • Define a class BankAccount with attributes such as account number, account holder name, and balance. Implement methods to deposit money, withdraw money, and display account information. • Create a class Student with attributes like roll number, name, marks in different subjects, etc. Implement methods to calculate total marks, average marks, and display student information. • Define a class vehicle with attributes like the vehicle's registration number, make, model, year of manufacture, and current mileage. Implement methods for setting and getting these attributes • Define a book and contain attributes such as title, author, ISBN, genre, and availability status. It should have methods for setting and getting these attributes. Dr.M.Sivakumar, AP/NWC 126