0% found this document useful (0 votes)
32 views129 pages

Oodp Unit-1

The document outlines a course on Object-Oriented Design and Programming, focusing on the principles of OOP, features of C++, and programming methodologies. It covers various topics including classes, objects, inheritance, polymorphism, and data encapsulation, along with practical programming skills such as method overloading and exception handling. The course aims to equip learners with the ability to create models using UML diagrams and develop programs using the object-oriented approach.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views129 pages

Oodp Unit-1

The document outlines a course on Object-Oriented Design and Programming, focusing on the principles of OOP, features of C++, and programming methodologies. It covers various topics including classes, objects, inheritance, polymorphism, and data encapsulation, along with practical programming skills such as method overloading and exception handling. The course aims to equip learners with the ability to create models using UML diagrams and develop programs using the object-oriented approach.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

21CSC101T OBJECT ORIENTED DESIGN

AND PROGRAMMING
Unit-1 - Introduction to OOPS

Dr.M.Sivakumar, AP/NWC 1
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

Dr.M.Sivakumar, AP/NWC 2
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
Dr.M.Sivakumar, AP/NWC 3
Introduction to Object-Oriented Programming, Features of C++

SESSION-01

Dr.M.Sivakumar, AP/NWC 4
OBJECT-ORIENTED PROGRAMMING

Dr.M.Sivakumar, AP/NWC 5
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

Dr.M.Sivakumar, AP/NWC 6
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.

Dr.M.Sivakumar, AP/NWC 7
Types of Programming Languages
• Machine level Language
• Assembly level Language
• High level Language
– Procedure oriented programming(POP) language
– Object oriented programming(OOP) language.

Dr.M.Sivakumar, AP/NWC 8
Procedure Oriented Programming Language

• Drawbacks
– Global data access
– It does not model real word problem very well
– No data hiding

Dr.M.Sivakumar, AP/NWC 9
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

Dr.M.Sivakumar, AP/NWC 10
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

Dr.M.Sivakumar, AP/NWC 11
Object Oriented Programming

Dr.M.Sivakumar, AP/NWC 12
Object Oriented Programming

Dr.M.Sivakumar, AP/NWC 13
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.
Dr.M.Sivakumar, AP/NWC 14
Object Oriented Programming
Vs Procedural Oriented Programming
Procedure Oriented Programming Object Oriented Programming
program is divided into small parts program is divided into parts called objects.
called functions
Importance is not given to data but to Importance is given to the data rather than
functions as well as sequence of procedures or functions because it works as a real
actions to be done. 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 objects can move and communicate with
function to function in the system each other through member functions.
It does not have any proper way for hiding data so OOP provides Data Hiding so provides more
it is less secure security
Overloading is not possible In OOP, overloading is possible in the form of
Function Overloading and Operator
Overloading.
Dr.M.Sivakumar, AP/NWC 15
Basic concepts of OOPS
1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing
Dr.M.Sivakumar, AP/NWC 16
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.

Dr.M.Sivakumar, AP/NWC 17
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.

Dr.M.Sivakumar, AP/NWC 18
Class and Objects

Dr.M.Sivakumar, AP/NWC 19
Class and Objects

Dr.M.Sivakumar, AP/NWC 20
Class and Objects

Dr.M.Sivakumar, AP/NWC 21
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

Dr.M.Sivakumar, AP/NWC 22
Data abstraction and encapsulation

Dr.M.Sivakumar, AP/NWC 23
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

Dr.M.Sivakumar, AP/NWC 24
Inheritance
• Inheritance is the process by which one object acquires the
properties of another object

Dr.M.Sivakumar, AP/NWC 25
Inheritance

Dr.M.Sivakumar, AP/NWC 26
Inheritance

Dr.M.Sivakumar, AP/NWC 27
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

Dr.M.Sivakumar, AP/NWC 28
Polymorphism

Dr.M.Sivakumar, AP/NWC 29
Dynamic binding

Dr.M.Sivakumar, AP/NWC 30
Message Passing

● What are Messages?

● Software objects interact and communicate with each


other by sending messages to each other.
Dr.M.Sivakumar, AP/NWC 31
Benefits of Object-Oriented programming
• Reuse of existing code
• Improved maintainability
• Often a ‘natural’ way to describe a system

Dr.M.Sivakumar, AP/NWC 32
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

Dr.M.Sivakumar, AP/NWC 33
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
Dr.M.Sivakumar, AP/NWC 35
Sample C++ Program

Dr.M.Sivakumar, AP/NWC 36
Features of C++

• Object-Oriented Programming (OOP)


• Procedural Programming
• Standard Template Library (STL)
• Memory Management
• Performance
• Portability with relatively few modifications
• Wide Usage

Dr.M.Sivakumar, AP/NWC 37
Difference between C and C++
C C++

Supports both procedural programming (like C)


Procedural programming language
and object-oriented programming (OOP)

Extends the syntax of C by adding new keywords


Simpler syntax
and features

Memory management is typically done manually operators like new and delete for dynamic
using functions like malloc and free 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
Dr.M.Sivakumar, AP/NWC 38
I/O Operations, Data Types, Variables -Static, Constants - Pointers

SESSION-02

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.
Dr.M.Sivakumar, AP/NWC 41
I/O Operations

Stream in C

Text Stream Binary Stream

Dr.M.Sivakumar, AP/NWC 42
Cascading of Input or Output Operators
• << 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;

Dr.M.Sivakumar, AP/NWC 43
Reading and Writing Characters and Strings
• char marks;
• cin.get(marks);//The value for marks is read
• OR
• marks=cin.get();//A character is read and assigned to marks
• string name;
• Cin>>name;

• string empname;
• cin.getline(empname,20);
• Cout<<“\n Welcome ,”<<empname;

Dr.M.Sivakumar, AP/NWC 44
Formatted Input and
Output Operations Formatted I/O

I/O class function and Manipulators


flages

Dr.M.Sivakumar, AP/NWC 45
Example
#include<iostream.h>
#define PI 3.14159
main()
{
cout.precision(3);
cout.width(10);
cout.fill(‘*’);
cout<<PI;
}
Output
*****3.142
Dr.M.Sivakumar, AP/NWC 46
Formatting with flags
• 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 .

Dr.M.Sivakumar, AP/NWC 47
Formatting with flags

Dr.M.Sivakumar, AP/NWC 48
Formatting Output Using Manipulators

Dr.M.Sivakumar, AP/NWC 49
Data Types in C++

Dr.M.Sivakumar, AP/NWC 50
Variables
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.

01 Local Variables 03 Instance variables

02 Static Variables 04 Constant Variables


Dr.M.Sivakumar, AP/NWC 51
Variables
Local Variables Instance Variables Static Variables Constant Variables

Static variables: Static variables are


Local variable: These are the also called as class variables. These
Instance variable: These are the
variables which are declared within variables have only one copy that is Constant is something that
variables which are declared in a
the method of a class. shared by all the different objects in doesn't change. In C language
class but outside a method,
constructor or any block. a class. and C++ we use the keyword
Example: Example: const to make program elements
Example:
public class Car
{
public class Car class Car constant.
{ { Example:
public:
private: public: const int i = 10;
// Method
// Created an instance variable //Static variable void f(const int i);
void display(int m)
String color;
{
Car(String c)
static int tyres; class Test
// Created a local variable void init() {
{
int model=m; { const int i;
color=c;
cout<<model; tyres=4; };
}
}
};
}; }
};

Dr.M.Sivakumar, AP/NWC 52
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
== (A == B) is not true.
becomes true.
Checks if the values of two operands are equal or not, if values are not equal
!= (A != B) is true.
then condition becomes true.
Checks if the value of left operand is greater than the value of right operand,
> (A > B) is not true.
if yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand, if
< (A < B) is true.
yes then condition becomes true.

Checks if the value of left operand is greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is less than or equal to the value of right
<= (A <= B) is true.
operand, if yes then condition becomes true.

Dr.M.Sivakumar, AP/NWC 57
Logical Operators
Operator Description Example

Called Logical AND operator. If both the operands are non-zero,


&& (A && B) is false.
then condition becomes true.

Called Logical OR Operator. If any of the two operands is non-zero,


|| (A || B) is true.
then condition becomes 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 !(A && B) is true.
false.

Dr.M.Sivakumar, AP/NWC 58
Bitwise Operators
Operator Description Example

Binary AND Operator copies a bit to the result if it exists in (A & B) will give 12 which is 0000
&
both operands. 1100
(A | B) will give 61 which is 0011
| Binary OR Operator copies a bit if it exists in either operand.
1101

Binary XOR Operator copies the bit if it is set in one operand (A ^ B) will give 49 which is 0011
^
but not both. 0001

(~A ) will give -61 which is 1100 0011


Binary Ones Complement Operator is unary and has the effect
~ in 2's complement form due to a
of 'flipping' bits.
signed binary number.

Binary Left Shift Operator. The left operands value is moved left A << 2 will give 240 which is 1111
<<
by the number of bits specified by the right operand. 0000

Binary Right Shift Operator. The left operands value is moved


>> A >> 2 will give 15 which is 0000 1111
right by the number of bits specified by the right operand.
Dr.M.Sivakumar, AP/NWC 59
Assignment Operators
Operator Description Example

Simple assignment operator, Assigns values from right side C = A + B will assign value of A + B
=
operands to left side operand. into C
Add AND assignment operator, It adds right operand to the left
+= C += A is equivalent to C = C + A
operand and assign the result to left operand.

Subtract AND assignment operator, It subtracts right operand


-= C -= A is equivalent to C = C - A
from the left operand and assign the result to left operand.

Multiply AND assignment operator, It multiplies right operand


*= C *= A is equivalent to C = C * A
with the left operand and assign the result to left operand.

Divide AND assignment operator, It divides left operand with


/= C /= A is equivalent to C = C / A
the right operand and assign the result to left operand.

Modulus AND assignment operator, It takes modulus using two


%= C %= A is equivalent to C = C % A
operands and assign the result to left operand.

Dr.M.Sivakumar, AP/NWC 60
Misc Operators
Operator Description Example

sizeof(a), where ‘a’ is integer, and will


sizeof() sizeof operator returns the size of a variable.
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.

&a; will give actual address of the


& Pointer operator & returns the address of a variable.
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++
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
Dr.M.Sivakumar, AP/NWC 62
Special Operators
Scope resolution operator

In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by using scope
1
resolution operator (::), because this operator allows access to the global version of a variable.

new Operator

2 The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the
memory and returns the address of the newly allocated and initialized memory to the pointer variable.

delete Operator
3 Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided delete operator by C++
.
language

Member Operator
4 C++ permits us to define a class containing various types of data & functions as members. To access a member using a pointer in the
object & a pointer to the member.

Dr.M.Sivakumar, AP/NWC 63
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.

Dr.M.Sivakumar, AP/NWC 64
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.
Dr.M.Sivakumar, AP/NWC 65
Real Time Example

Dr.M.Sivakumar, AP/NWC 66
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;
Output:
return 0; Value of var variable: 20
} Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Dr.M.Sivakumar, AP/NWC 67
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 OUTPUT:
p = arr; 0
1
for(int i=0; i<6;i++) 2
{ 3
cout<<*p<<endl; 4
//++ moves the pointer to next int position 5
6
p++;
}
return 0;
Dr.M.Sivakumar, AP/NWC 68
}
this Pointers
• this pointer hold the address of current object

• int num;

• This->num=num;

Dr.M.Sivakumar, AP/NWC 69
#include <iostream>
this Pointers Example
using namespace std;
class Employee int main(void)
{ {
int id; //data member (also instance variable) Employee e1 =Employee(101, "Sonoo", 890000);
char name[20]; //data member(also instance variable) //creating an object of Employee
float salary; Employee e2=Employee(102, "Nakul", 59000);
public: //creating an object of Employee
e1.display(); e2.display(); return 0;
Employee(int id, string name, float salary)
}
{
this->id = id;
this->name = name;
this->salary = salary;
} Output:
void display() 101 Sonoo 890000
{ 102 Nakul 59000
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
Dr.M.Sivakumar, AP/NWC 70
Function using pointers
#include<iostream> void swap(int *a,int *b)
using namespace std; {
void swap(int *a ,int *b ); int c;
//Call By Reference c=*a;
int main() *a=*b;
{ *b=c;
int p,q; }
cout<<"\nEnter Two Number You Want To Swap \n";
cin>>p>>q; Output:
swap(&p,&q); Enter Two Number You Want to Swap
cout<<"\nAfter Swapping Numbers Are Given below\n\n"; 10 20
cout<<p<<" "<<q<<" \n"; After Swapping Numbers Are Given below
return 0; 20 10
}

Dr.M.Sivakumar, AP/NWC 71
MCQ

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

Dr.M.Sivakumar, AP/NWC 72
MCQ

a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a

Dr.M.Sivakumar, AP/NWC 73
MCQ
What is output of the following code?
#include <iostream>
using namespace std;
int main()
{
char arr[20];
int i;
for(i = 0; i < 10; i++)
*(arr + i) = 65 + i;
*(arr + i) = '\0';
cout << arr;
return(0);
}

Dr.M.Sivakumar, AP/NWC 74
MCQ

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.

Dr.M.Sivakumar, AP/NWC 75
Type Conversions,
Conditional and Looping Statements

SESSION-03

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

Dr.M.Sivakumar, AP/NWC 77
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;
} Output:
The value of num1 is: 25
Dr.M.Sivakumar, AP/NWC The value of num2 is: 25 78
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

Dr.M.Sivakumar, AP/NWC 82
Arrays - C++ 11 features

SESSION-04

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


Dr.M.Sivakumar, AP/NWC 84
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++ )
{
Element Value
n[ i ] = i + 100; // set element at location i to i + 100 0 100
} 1 101
cout << "Element" << setw( 13 ) << "Value" << endl; 2 102
// output each array element's value 3 103
for ( int j = 0; j < 10; j++ ) 4 104
{ 5 105
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl; 6 106
} 7 107
return 0; 8 108
} 9 109

Dr.M.Sivakumar, AP/NWC 85
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
Dr.M.Sivakumar, AP/NWC 86
Class and Objects, Abstraction and
Encapsulation

SESSION-05

Dr.M.Sivakumar, AP/NWC 87
CLASS AND OBJECTS, ABSTRACTION AND
ENCAPSULATION

Dr.M.Sivakumar, AP/NWC 88
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
}
// ...
};

Dr.M.Sivakumar, AP/NWC 90
Class
• Class is just a blue print, which declares and defines Example
class Room
characteristics and behavior, namely data members {
public:
and member functions respectively.
double length;
• All objects of this class will share these characteristics double breadth;
double height;
and behavior.
double calculateArea()
• Class name must start with an uppercase
{
letter(Although this is not mandatory). return length * breadth;
}
Example,
double calculateVolume()
class Student
{
return length * breadth * height;
}

Dr.M.Sivakumar, AP/NWC }; 91
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; int Account::count=0;
class Account int main(void)
{ {
public: Account a1 =Account(201, "Sanjay");
int accno; //data member (also instance variable) //creating an object of Account
string name; Account a2=Account(202, "Nakul");
static int count; Account a3=Account(203, "Ranjana");
Account(int accno, string name) // Constructor Function a1.display();
{ a2.display();
this->accno = accno; a3.display();
this->name = name; cout<<"Total Objects are: "<<Account::count;
count++; return 0;
} }
void display()
{
cout<<accno<<" "<<name<<endl; Output:
} 201 Sanjay
}; 202 Nakul
203 Ranjana
Total Objects are: 3
Dr.M.Sivakumar, AP/NWC 95
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
keyword Class Name

class Rectangle int main()


{ { Object
private: creation
Rectangle r2;
int width, length; Inside the
member function r1.set(5,8); function
public:
int x=r1.area();
void set (int w, int l);
int area() cout<<"x value in r1 "<<x;
{ inside the class r2.set(5,8);
return width*length; int x=r1.area();
} cout<<"x value in r2 "<<x;
};
void Rectangle :: set (int w, int l) }
{
width = w;
Member function
length = l;
}

class name scope operator outside the class Dr.M.Sivakumar, AP/NWC 97


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;
int main()
class sample
{ {
private: const sample s(20);
int val; sample s1(2);
public:
cout << "The value using object d : " << s.getValue();
sample(int x = 0)
{ cout << "\nThe value using object d1 : " <<
val = x; s1.getValue();
}
return 0;
int getValue() const
{ }
return val;
}
};

Dr.M.Sivakumar, AP/NWC 99
Access Specifiers, Methods

SESSION-06

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
Public anywhere in the
program, including
outside the class.

•Private members can


Private only be accessed from
within the class itself.

•Protected members
can be accessed from
Protected within the class itself,
from derived classes
and from friend
function
Example: public
#include<iostream>
using namespace std; void student::display()
class student {
{ cout<<"Name:"<<name<<endl;
public: cout<<"Age:"<<age;
char name[20]; }
int age;
void display();
};
int main()
Output:
{
Enter name:raja
student s1;
Enter age:20
cout<<"Enter name:";
Name:raja
cin>>s1.name;
Age:20
cout<<"Enter age:";
cin>>s1.age;
s1.display();
return 0;
}
Example: private
#include<iostream> void student::getdata()
using namespace std; {
class student cout<<"Enter name:";
{ cin>>name;
private: cout<<"Enter age:";
char name[20]; cin>>age;
int age; }
public: void student::display()
void getdata(); {
void display(); cout<<"Name:"<<name<<endl;
}; cout<<"Age:"<<age;
int main() }
{
student s1;
//cin>>s1.name; Output:
//cin>>s1.age; Enter name:raja
s1.getdata(); Enter age:21
s1.display(); Name:raja
return 0; Age:21
}
Example: protected
#include<iostream>
using namespace std; void student::getdata()
class person {
{ cout<<"Enter name:";
protected: cin>>name;
char name[20]; cout<<"Enter age:";
int age; cin>>age;
}; }
class student: public person void student::display()
{ {
public: cout<<"Name:"<<name<<endl;
void getdata(); cout<<"Age:"<<age;
void display(); }
};
int main() Output:
{ Enter name:raja
student s1; Enter age:22
s1.getdata(); Name:raja
s1.display(); Age:22
return 0;
}
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
UML Diagrams Introduction – Use Case Diagram, Class Diagrams

SESSION-07

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.

Dr.M.Sivakumar, AP/NWC 110


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.

Dr.M.Sivakumar, AP/NWC 111


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)

Dr.M.Sivakumar, AP/NWC 112


Use Case Diagram

Dr.M.Sivakumar, AP/NWC 113


Use Case Diagram

Dr.M.Sivakumar, AP/NWC 114


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: - ClassName
– Public: +
– Protected: # Attributes
– Static: Underlined
(i.e. shared among all members
Behaviours
of the class) 115

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 ClassName
– Class name
– Class attributes (i.e. data members, variables) Attributes
– Class operations (i.e. methods)
Behaviours
•The relation between different classes makes up
a class diagram

Dr.M.Sivakumar, AP/NWC 116


Class Diagram Example

Name
Account_Name
- Customer_Name
Attributes
- Balance
+addFunds( ) Operations
+withDraw( )
+transfer( )

Dr.M.Sivakumar, AP/NWC 117


Class Diagram Example

Dr.M.Sivakumar, AP/NWC 118


Basic components of a class diagram
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
Class Name
an object.
• Middle section: Contains the attributes of the class. Use this Attributes
section to describe the qualities of the class. This is only required
when describing a specific instance of a class. Behaviors

• 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.

Dr.M.Sivakumar, AP/NWC 119


RULES TO BE FOLLOWED
• 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.
Dr.M.Sivakumar, AP/NWC 120
Attributes : Second Section
• 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
Dr.M.Sivakumar, AP/NWC 121
Methods : Third section
• 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

Dr.M.Sivakumar, AP/NWC 122


Relationships

Dr.M.Sivakumar, AP/NWC 123


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

Dr.M.Sivakumar, AP/NWC 129

You might also like