Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 270

21CSC101T - Object Oriented

Design and Programming:

UNIT 1

McGraw-Hill ©The McGraw-Hill Companies, Inc., 2000


Learning Resources
1. Grady Booch, Robert A. Maksimchuk, Michael W. Engle, Object- Oriented
Analysis and Design withApplications,3rd ed.,Addison-Wesley,May2007
2. Reema Thareja, Object Oriented Programming with C++, 1st ed., Oxford
University Press, 2015
3. Sourav Sahay, Object Oriented Programming with C++,2nd ed.,Oxford University
Press,2017
4. Robert Lafore, Object-Oriented Programming in C++,4th ed., SAMS
2
Publishing, 2008
5. Ali Bahrami, Object Oriented Systems Development”, McGrawHill, 2004
6. Craig Larmen, Applying UMLandPatterns,3rd ed.,Prentice Hall,2004
7. Object-Oriented Programming with C++, by E. Balagurusamy
04/09/2024 Object Oriented Design and
UNIT 1 SYLLABUS

 Comparison of Procedural programming and Object-Oriented Programming

 OOPs and its features

 Data Types, Variables, static, constant, pointers, type conversions

 Classes and objects with Examples

 OOPS Features - Encapsulation /Abstraction and application

 Access Specifiers

 Inline functions, friend functions

 UML Diagrams- Introduction, Class diagram, and its components

 Class diagram relations and its multiplicity

 UML use case diagram, use case, scenario

 use case diagram objects and relations


Book to follow


Object-Oriented Programming in C++, 4th Edition by Robert Lafore The
C++ Programming Language, 4th Edition by Bjarne Stroustrup

04/09/2024 Object Oriented Design and


EVOLUTION

To write a program for a computer, we must use a computer language.


A computer language is a set of predefined words that are combined into a program
according to predefined rules (syntax).
Over the years, computer languages have evolved from machine language to high-
level languages.

9.5

04/09/2024 Object Oriented Design and


Machine languages
In the earliest days of computers, the only programming languages available were
machine languages.
Each computer had its own machine language, which was made of streams of 0s and
1s.
In a primitive hypothetical computer, we need to use eleven lines of code to read two
integers, add them and print the result.
These lines of code, when written in machine language, make eleven lines of binary
9.6

code, each of 16 bits, as shown in next slide.

The only language understood by a computer is


machine language.
04/09/2024 Object Oriented Design and
Assembly languages

The next evolution in programming came with the idea of replacing binary code for
instruction and addresses with symbols or mnemonics.
Because they used symbols, these languages were first known as symbolic
languages.
The set of these mnemonic languages were later referred to as assembly languages.
The assembly language for our hypothetical computer to replace the machine
9.7

language in previous slide.


The only language understood by a computer is
machine language.
04/09/2024 Object Oriented Design and
High-level languages

Although assembly languages greatly improved programming efficiency, they still


required programmers to concentrate on the hardware they were using.
Working with symbolic languages was also very tedious because each machine
instruction had to be individually coded.
The desire to improve programmer efficiency and to change the focus from the
computer to the problem being solved led to the development of high-level
languages.
9.8

Over the years, various languages, most notably BASIC, COBOL, Pascal, Ada, C,
C++, and Java, were developed.

04/09/2024 Object Oriented Design and


9.9

04/09/2024 Object Oriented Design and


Translation

Programs today are normally written in one of the high-level languages.


To run the program on a computer, the program needs to be translated into the
machine language of the computer on which it will run.
The program in a high-level language is called the source program.
The translated program in machine language is called the object program.
Two methods are used for translation: compilation and interpretation.
9.10

04/09/2024 Object Oriented Design and


Compilation
A compiler normally translates the whole source program into the object program.

Interpretation

Some computer languages use an interpreter to translate the source program into the
object program.
Interpretation refers to the process of translating each line of the source program into
the corresponding line of the object program and executing the line.
9.11

However, we need to be aware of two trends in interpretation: that used by some


languages before Java and the interpretation used by Java.

04/09/2024 Object Oriented Design and


Programming paradigm
• Different approaches to build to specific type
solutions problems of

12

04/09/2024 Object Oriented Design and


Programming Paradigms

Today, computer languages are categorized according to the approach they use to
solve a problem.
A paradigm, therefore, is a way in which a computer language looks at the problem
to be solved.
We divide computer languages into four paradigms: procedural, object-oriented,

9.13
functional and declarative. Figure summarizes these.

04/09/2024 Object Oriented Design and


9.14

Categories of programming languages


04/09/2024 Object Oriented Design and
Software Evolution
The Procedural Paradigm
In the procedural paradigm (or imperative paradigm) we can think of a program as an
active agent that manipulates passive objects.
We encounter many passive objects in our daily life: a stone, a book, a lamp, and so
on. A passive object cannot initiate an action by itself, but it can receive actions from
active agents.
A program in a procedural paradigm is an active agent that uses passive objects that
we refer to as data or data items. To manipulate a piece of data, the active agent
9.16

(program) issues an action, referred to as a procedure.


For example, think of a program that prints the contents of a file. The file is a passive
object. To print the file, the program uses a procedure, which we call print.

04/09/2024 Object Oriented Design and


9.17

The concept of the procedural paradigm


04/09/2024 Object Oriented Design and
A program in this paradigm is made up of three parts: a part for object creation, a
set of procedure calls and a set of code for each procedure. Some procedures have
already been defined in the language itself. By combining this code, the
programmer can create new procedures.

9.18

04/09/2024The Object
components ofOriented Design andprogram
a procedural
Glimpse on Procedural
Programming
Procedural Programming

Using function
Function & program is divided into modules
Every module has its own data and function which can be called by other
modules.
Some Procedural Languages
 FORTRAN (FORmula TRANslation)

 COBOL (COmmon Business-Oriented Language)

 Pascal

C

9.21  Ada

04/09/2024 Object Oriented Design and


The hitch…
The BURNING questions in mind…

• Oh no… Why another Programming Language ?


• What would we do with it, we already know C?
• Will it really help improve my programming skills?

Object Oriented Design and Programming


04/09/2024 22
The Object-Oriented
Paradigm
The object-oriented paradigm deals with active objects instead of passive objects.

We encounter many active objects in our daily life: a vehicle, an automatic door, a
dishwasher and so on.

The action to be performed on these objects are included in the object: the objects
need to only receive the appropriate stimulus from outside to perform one of the
actions.

A file in an object-oriented paradigm can be packed with all the procedures—called


methods in the object-oriented paradigm—to be performed by the file: printing,
copying, deleting and so on.

The program in this paradigm just sends the corresponding request to the object.
The concept of an object-oriented paradigm
Mind Map on C Programming
A Better C
C++
Improves on many of C's features
Has object-oriented capabilities
• Increases software quality and reusability
Developed by Bjarne Stroustrup at Bell Labs
• Called "C with classes“ an enhanced version of C
Superset of C
• Can use a C++ compiler to compile C programs
• Gradually evolve the C programs to C++
 Hybrid language
26
C-like style
Object-oriented style
BothTowards better programming….

Object Oriented Design and


04/09/2024
Comparison
Procedural Oriented Object Oriented

Program is divided into small Program is divided into small


parts called ‘Functions’ parts called ‘Objects’

Has access specifiers :


Global and Local
Public, Private,
data
Protected
Doesn’t have any proper way
Provides data hiding and
for hiding data
27 security

Eg: C, VB, FORTAN Eg: C++, JAVA, VB.NET

04/09/2024 Object Oriented Design and


28

04/09/2024 Object Oriented Design and


OOP Introduction
• Object-oriented (OOP) is a programming
programming
paradigm based upon objects (having both data and methods)
that aims to incorporate the advantages of modularity and
reusability.
Objects, which are usually instances of classes, are used to

interact with one another to design applications and computer
programs.
Objects have both data and methods
Objects of the same class have the same data elements and
methods
29
Objects send and receive messages to invoke actions

Key idea in object-oriented:

The real world can be accurately described


as a collection of objects
04/09/2024 that Design
Object Oriented interact.
and
WHY OOP ?

 Save development time (and cost) by reusing


code
 once an object class is created it can be used in other applications

 Easier debugging
30  classes can be tested independently
 reused objects have already been tested

04/09/2024 Object Oriented Design and


Object oriented programming
• Component of a program that knows how to perform
certain actions and how to interact with other elements of the
program

I am going to walk
(method)

31

04/09/2024 Object Oriented Design and


32

04/09/2024 Object Oriented Design and


33

04/09/2024 Object Oriented Design and


Features of OOP`
• Bottom–up approach in program design

• Programs organised around objects, grouped in classes

• Focus on data with methods to operate upon object’s data

• Interaction between objects through functions

• Reusability of design through creation of new classes by


adding features to existing classes

04/09/2024 Object Oriented Design and


04/09/2024 Object Oriented Design and
1.INTRODUCTION
TO OBJECT
• Objects are key to understanding object-oriented technology

• In real life, things that you see such as cars, trees, cats, mobile phones and so
on are objects. Even, you as a student is object.

ELEMENTS OF AN OBJECT Attribute/ • properties used to define


state characteristics
• means the object can perform
Behaviour actions & can have actions
performed on it.
• means the object can be called &
Identity
used as a single unit.

04/09/2024 Object Oriented Design and


ATTRIBUTE STATE
We used it to save the information of Attribute also can describe about
object state of object
Every object was different of attribute Example:
such as type, quality. Current gear (1/2/3/4/5)
Engine (on/of)
Car This attribute will declare as variable
color: red, blue
category: sport, turbo, door
type: proton, perodua

04/09/2024 Object Oriented Design and


38
39
BEHAVIOR

It can tell what the process can do/will be doing


Example:
Start engine
Speeding
Change gear
Stop
EXAMPLE 1:

An air-conditioner in the bedroom is an object


-state:  turn on
 current temperature is at 20 degree Cel.

-behaviour : change the temperature level

41
EXAMPLE 2

-state:  dark brown colours on its


face, ears and feet

-behaviours :  playing, fighting,


hunting

42

A Siamese cat
EXAMPLE 3
How about the following cats?
•They are 3 different cats in which two of them are of the same type.
•What makes them different?
 their states, behaviors and identities

43
EXAMPLE 4:

Different type of cats

share the same behaviours.


44
EXAMPLE 5:
• How about these cars?
• Try to identify their common attributes
and behaviors

45

car
WHAT CAN BE CONCLUDED FROM
EX 3 - 5 ?

A group of animals or things that are similar in some way.


They share the same attributes and behaviours.

This group of objects represents a class.

46
Basic Terminology

 object
usually a person, place or thing (a noun)
 method
an action performed by an object (a verb)
 attribute

47 description of objects in a class


 class
a category of similar objects (such as automobiles)
does not hold any values of the object’s attributes
04/09/2024 Object Oriented Design and
OBJECTS
An object has:

state - descriptive characteristics

behaviors - what it can do (or what can be done to it)

The state of a bank account includes its account number and its current balance

The behaviors associated with a bank account include the ability to make deposits
and withdrawals

Note that the behavior of an object might change its state


2. CLASSES
• An object is defined by a class
• A class is the blueprint of an object
• The class uses methods to define the behaviors of the object
• A class represents a concept, and an object represents the embodiment of that
concept
• Multiple objects can be created from the same class
CLASS VS OBJECT

Class Object
a thing, both tangible
a kind of template.
and intangible.
represents the common is comprised of data &
structure & behaviour operations that
shared by the same type. manipulate these data.
A collection of objects is called an instance of
of similar type. a class.
must be defined before
creating an instance of
the class.
CLASS VS OBJECT
Object ,Object and Object

A student, a professor
A desk, a chair, a classroom, a building
A university, a city, a country
A subjects such as Physics, Math, History, …

Object contains data and code to manipulate that data

52

Object Oriented Design and


04/09/2024
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”.

53

04/09/2024 Object Oriented Design and


CHARACTERISTICS/CONCEPTS
/FEATURES OF OOP

Abstraction Encapsulation

54

Inheritance Polymorphism
Abstraction and Encapsulation

ABSTRACTION refers to the act of representing essential features


without including the background details or explanations.

It focuses upon the observable behavior of an object.


The wrapping up of data and operations /
functions (that operate on the data ) into a
single unit (called class) is known as
ENCAPSULATION.

Encapsulation is a way to implement data


abstraction. It hides the details of the
implementation of an object.

It focuses upon the implementation that


gives rise to observable behavior.
Abstraction & Encapsulation

Abstraction is the concept of object- Encapsulation is a method of making a


oriented programming that "shows" only complex system easier to handle for end
essential attributes and "hides" users. The user need not worry about
unnecessary information. The main internal details and complexities of the
purpose of abstraction is to hide the system. Encapsulation is a process of
unnecessary details from the users. wrapping the data and the code, that
Abstraction is selecting data from a larger operate on the data into a single entity.
pool to show only relevant details of the You can assume it as a protective wrapper
object to the user. It helps in reducing that stops random access of code defined
programming complexity and effort. outside that wrapper.

56
Inheritance and class hierarchy

Inheritance is the capability of one class of things to inherit capabilities or


properties from other class
Why ?

Capability to express the inheritance relationship which makes it ensure closeness with
real world models.

Idea of reusability.
It allows addition of additional features to an existing class without modifying it.
A subclass defines only those features which are unique to it.
Inheritance Example(cont.)

Person

Student Employee

Undergraduat Graduate Staff Faculty


e
Polymorphism

It is the ability for a message or data to be


processed in more than one form.

It is a property by which the same message can be


sent to objects of several different classes, & each
object can respond in a different way depending
on its class.

Ex : Addition operation

On Numbers gives sum and on String it


concatenates

Operator Overloading

Function Overloading
Polymorphism

What you learn?

LEARN()
Message passing
• Objects communicate with each other

• They communicate by sending and receiving information (similar to people


passing messages)

• Message – request for execution of a procedure, i.e it invokes a function

• E.g employee.salary(name)

where employee – object, salary – message and name –


information/data

•Message passing involves :

• Specifying the name of the object.

• Name of the function(message).

• Information to be sent.
Student Class

62

04/09/2024 Object Oriented Design and


INTRODUCTION TO C++

-Data Types, Variables, static, constant, pointers, type conversions


General structure of C++ (1)
Basic Structure of a C++ Program Example
Documentation Section /*
[ Used for Comments about Basic C++ Program to define a
Program] structure of C++ Program */
Pre-processor Section #include<iostream>
using namespace std;

Definition Section [ some functions may be defined here


]
Global Declaration Section int area (int r);
[ Global Declarations /function
definitions]
main () void main ()
{ { int radius;
/* Declaration Part float a;
Executable Part */ cin >> radius;
a=area(radius);
} cout<<a;
}

Sub Program Section float area (int r)


[ User defined Functions] { float p;
p=PI*r*r;
return P;
}
General structure of C++ (2)
Documentation Section
details associated with the program
usually gives the name of the program, the details of the author and other details
like the time of coding and description.
Preprocessor Section
used to link system library files, for defining the macros and for defining the
conditional inclusion
Global Declaration Section
All the global variable /user defined used are declared in this part
Main Function Section
Every programs needs to have the main function. Each main function contains 2
parts. A declaration part and an Execution part. The declaration part is the part
where all the variables are declared. The execution part begins with the curly
brackets and ends with the curly close bracket. Both the declaration and execution
part are inside the curly braces.
Sub Program Section
All the user-defined functions are defined in this section of the program.
To Write a Simple Program

Before writing the programs


Comments
Document programs
Improve program readability
Ignored by compiler
Single-line comment
Use C’s comment /* .. */ OR Begin with // or
Preprocessor directives
66
Processed by preprocessor before compiling
Begin with #
Basics of a C++ Program

Common Input/output functions


cin
Standard input stream
Normally keyboard
cout
Standard output stream
Normally computer screen
cerr
Standard error stream
67
Display error messages
Basics of C++ program

/* First C++ Program */ /*...*/ comments are used for the documentation to
understand the code to others. These comments are ignored by the compiler

#include<iostream> It is a preprocessor directive. It contains the contents of


iostream header file in the program before compilation. This header file is
required for input output statements.
Structure of C++ program
int/void -Integer (int) returns a value. In the above program it returns value
0. Void does not return a value so there is no need to write return keyword.

main() It is an entry point of all the function where program execution
begins.
Curly Braces {...}It is used to group all statements together.

std::cout. It is requried when we use #include . Std::cout defines that we are


using a name (cout) which belongs to namespace std.

Namespace is a new concept introduced by ANSI where C++ standard


libraries are defined.

If using namespace std is placed into the program then it does not required to
write std:: throughout the code. Namespace std contains all the classes,
objects and functions of the standard C++ library.
Data Types
A type defines a set of values and a set of operations that can be applied on those
values. The set of values for each type is known as the domain for the type.
Data types in C++ is mainly divided into two types:
Primitive Data Types: These data types are built-in or predefined data types and can
be used directly by the user to declare variables. Primitive data types includes:
Integer
Character
Boolean
Floating Point
Double Floating Point
Valueless or Void
Wide Character
Also : String

Abstract or user defined data type: These data types are defined by user itself. Like,
defining a class in C++ or a structure.
Data Types
Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of
memory space and ranges from -2147483648 to 2147483647.

Character: Character data type is used for storing characters. Keyword used for character
data type is char. Characters typically requires 1 byte of memory

Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable
can store either true or false. Keyword used for boolean data type is bool.

Floating Point: Floating Point data type is used for storing single precision floating point
values or decimal values. Keyword used for floating point data type is float. Float variables
typically requires 4 byte of memory space.

Double Floating Point: Double Floating Point data type is used for storing double precision
floating point values or decimal values. Keyword used for double floating point data type is
double. Double variables typically requires 8 byte of memory space.
void: Void means without any value. void data type represents a valueless entity. Void data
type is used for those function which does not returns a value.

Wide Character: Wide character data type is also a character data type but this data type has
size greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4
bytes long.
Data Types

Datatype Modifiers: As the name implies, datatype modifiers are used with the
built-in data types to modify the length of data that a particular data type can
hold.

Data type modifiers available in C++ are:


• Signed
• Unsigned
• Short
• Long
DATA TYPES
String

The string Type


a programmer-defined type
requires #include <string>
A string is a sequence of characters
"Hi Mom"
"We're Number 1!"
"75607"
C++ program using data
types
// C++ program to sizes of data types bytes" <<endl;
#include<iostream> cout << "Size of double : " << sizeof(double)
using namespace std; << " bytes" << endl;
int main() cout << "Size of wchar_t : " << sizeof(wchar_t)
{ << " bytes" <<endl;
cout << "Size of char : " << sizeof(char) << " return 0;
byte" << endl; }
cout << "Size of int : " << sizeof(int) << "
bytes" << endl;
cout << "Size of short int : " << sizeof(short int)
<< " bytes" << endl;
cout << "Size of long int : " << sizeof(long int)
<< " bytes" << endl;
cout << "Size of signed long int : " <<
sizeof(signed long int) << " bytes" << endl;
cout << "Size of unsigned long int : " <<
sizeof(unsigned int) << " bytes" << endl;
cout << "Size of float : " << sizeof(float) << "
Variables
A variable definition means to tell the compiler where and
how much to create the storage for the variable.
Rules for identifiers
must begin with letter or the underscore _
followed by any combination of numerals or
letters
recommend meaningful identifiers
Declarations

Constants and variables must be declared before they can be used.

• A constant declaration specifies the type, the name and the value
of the constant.
• A variable declaration specifies the type, the name and possibly
the initial value of the variable.

When you declare a constant or a variable, the compiler:


1. Reserves a memory location in which to store the value of the
constant or variable.
2. Associates the name of the constant or variable with the
memory location.
Variable declarations

Variables are used to store values that can be changed during the
program execution.
A variable is best thought of as a container for a value.
Syntax:
< type > < identifier >;
< type > < identifier > = < expression>;

Examples:
int sum; //single declaration
float p,q,r; //multiple declaration
char answer = 'y';
double temperature = -3.14;
Variable declarations
• A variable has a type and it can contain only values of that type.
For example, a variable of the type int can only hold
integer values.
• Variables are not automatically initialized.
For example, after declaration
int sum;
the value of the variable sum can be anything (garbage).

Thus, it is good practice to initialize variables when they are


declared.
Once a value has been placed in a variable it stays there until the
program deliberately alters it.
Variable declarations

int i; // declared but not initialised


char c;
int i, j, k; // Multiple declaration
int i=0; // declaration
i = 10; // initialization
int i=10; //initialization and declaration in same step
int i=10, j=11;
Variable Declaration

#include <iostream>
using namespace std;
int main ()
{
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
cout<<c<<endl<<f;
return 0;
}
cin and the Extraction Operator >>

cin >> variable-name;


Meaning: read the value of the variable called <variable-name> from the
user

Example:
cin >> a;
cin >> b >> c;
cin >> x;
cin >> my-character; 82
cout and the insertion Operator <<

cout << variable-name;


Meaning: print the value of variable <variable-name> to the user
cout << “any message “;
Meaning: print the message within quotes to the user
cout << endl;
Meaning: print a new line
Example:
cout << a;
cout << b << c; 83
cout << “This is my character: “ << my-character << “ he he he”
<< endl;
Static Variable

When the static keyword preceded the declaration of a variable, that variable becomes a
static variable.

A static keyword serves a different purpose depending on where it has been declared.
• If it is declared inside of a class, all instances of the class (i.e. objects) will share the
same copy of the variable, and we can access it without any object by class name
outside the class.
• If it is declared inside of a function then its value is preserved between successive
calls for the lifetime of the program, but it cannot be accessd outside the scope or
function in which it is declared.
84

• Syntax
• static <type> <variable_name>;

04/09/2024 Object Oriented Design and


Special types of variable-static

• Static –
These variables holds their value between function calls.

#include <iostream.h>
using namespace std;
int main()
{

static int y=20;


}
Using the Static Storage Class
Specifier

Using the static storage class specifier on a variable that normally would
be automatic makes the variable static

Can use the static storage class specifier with variables declared inside
functions

When the function is called the first time….


· Variable is created and initialized to zero
· Remains in existence for the remainder of the program
· Scope of the variable remains unchanged
· Can be used only in the block that declared it
Example :Static Variable inside a Function

#include <iostream>
using namespace std;
This proves that the
void increase(){ static variable inside a
static int num = 0;
cout << ++num << endl; function is declared only
} once on the first function
call and the remaining
int main(){ successive function calls
increase();
87
increase(); use the same copy.
return 0;
}

04/09/2024 Object Oriented Design and


Static example

#include<iostream> }
using namespace std;
int main() {
void func() { cout << "Calling Function :- " <<
static int count = 0; endl;
/* value of 'count' persist between func();
function calls cout << "Calling Function :- " <<
* i.e count doesn't become 0 endl;
every time func() is called; func();
* previous value of count cout << "Calling Function :- " <<
remains alive endl;
*/ func();
count++; return 0;
cout << "Function is called " << }
count << " times " << endl;
Static Variable

• A static variable within a class is shared by all the objects of the


class.
• A static variable inside a scope or function remains in the memory for
the lifetime of the program.
• We should use a static variable whenever we want to reuse the modified value of the
variable inside a function in the next function call.
Or

89 • when we want all the objects to maintain a single copy of the class variable.

04/09/2024 Object Oriented Design and


Constants in C

Constants refer to fixed values called literals. Ie., their


values cannot be modified after their definition.

Constants can be of any of the basic data types like


an
integer constant - 0213 , 0x4b ,212 , 215u ,0xFeeL , 23ul
a floating constant - 3.14159 314159E-5L,
a character constant ‘x, an escape sequence (e.g., '\t'),
string literal.
There are enumeration constants as well.
Special Character Constant
Defining Constants

Using #define preprocessor


#define identifier value
eg. #define MAX_STRENGTH 55
Using const keyword.
const type variable = value;
eg. const int Max_Strength=55;
Enum – used to assign names to const
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{ enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Type Conversions
C++ facilitates type conversion into 2 forms :
Implicit Type Conversion - performed by the compiler without
programmer’s intervention.

• The C++ compiler converts all operands upto the type of the largest
operand, which is called type promotion.

Explicit Type Conversion


Explicit conversion can be done using type cast operator and the
general syntax for doing this is :

datatype (expression);
Type Conversions

#include <iostream>
using namespace std;
void main(){
int a;float b,c;
cout << "Enter the value of a:";
cin >> a;
cout << "Enter the value of b:";
cin >> b;
c = float(a)+b;
cout << "The value of c is:" << c;
Type Cast Operator

C++ permit explicit type conversion of variables or expressions using the type cast
operator.
o (type-name) expression // C notation

o type-name ( expression ) // C++ notation


// like a function call
// notation
eg:- average = sum /(float) i; // C notation
average = sum / float(i); // C++ notation
Type Cast Operator

continue…

p = int * ( q ); // is illegal

p = ( int * ) q; // is legal

Alternatively, we can use typedef to create an identifier of the


required type.

typedef int * int_pt;


p = int_pt ( q );
Type Conversions
A cast is a special operator that forces one data type to be converted into another. As an
operator, a cast is unary and has the same precedence as any other unary operator.

we have four specific casting operators:

static_cast <new_type> (expression) - The static_cast operator performs a nonpolymorphic


cast. For example, it can be used to cast a base class pointer into a derived class pointer.

const_cast <new_type> (expression) - The const_cast operator is used to explicitly override


const and/or volatile in a cast.

dynamic_cast <new_type> (expression) - The dynamic_cast performs a runtime cast that


verifies the validity of the cast. If the cast cannot be made, the cast fails and the expression
evaluates to null.

reinterpret_cast <new_type> (expression) - The reinterpret_cast operator changes a pointer


to any other type of pointer.
Scope Resolution Operator continue…

C++ is a block structured language. The scope


of a variable extends from the point of its
declaration till the end of the block containing
the declaration.

A variable declared inside a block is said to be


local to that block.
Blocks in C++ are often nested.

In C, the global version of a variable can not


be accessed from within the inner block.

C++ resolved this problem with the use of the


scope resolution operator ( :: ).
Usage of Scope Resolution
Operator

Scope resolution operator in C++ can be used for:


1. Accessing a global variable when there is a local variable with same name
2. Defining a function outside a class
3. Accessing a class’s static variables
4. Referring to a class inside another class
99 5. In case of multiple Inheritance
6. Namespace

04/09/2024 Object Oriented Design and


Scope Resolution Operator

Accessing a global variable when there is a local variable with same name

The scope resolution operator


( :: ) can be used to uncover a #include<iostream.h>
hidden variable. #include<conio.h>
int m = 10;
: : variable-name void main( )
{
This operator allows access to int m = 20;
cout << "m_local = " << m << "\
the global version of a variable. n";
cout << "m_global = " <<::m << "\
n";
}
#include<iostream>
using namespace std;
// Defining a static
class Try
members explicitly using
{
::
static int num1;
int Try::num1 = 10;
public:
int Try::num2 = 15;
static int num2;
int main()
// Local parameter hides class member
{
// Class member can be accessed it using ::
Try o;
void function(int num1)
int num1 = 20 ;
{
o.function(num1);
// num1 static variable can be accessed using ::
10
1 cout << "nTry::num2 = "
// inspite of local variable num1
<< Try::num2;
cout << "Static num1: " << Try::num1;
return 0;
cout << "nLocal num1: " << num1;
}
}
}; 04/09/2024 Object Oriented Design and
Operators

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Sizeof() Operators
Control Flow
Lab Exercise – Work Order #1

1. Write a C++ program to convert input temperature from Celsius to Fahrenheit.


2. Write a C++ program to find the sum of n natural number.
3. Write a C++ program to read three integers and print the sum, product, average,
largest and smallest
4. Write a C++ program to input a 4-digit number and check if it is divisible by
2,3,4,12
5. Write a C++ program to input a 4-digit number and display the sum of its digits
6. Write a C++ program to find the factorial of a given number
7. Write a C++ program to generate Fibonacci series up to n terms
8. Write a C++ program to convert decimal to binary , octal and hexadecimal
9. Write a C++ program to check if a number is Armstrong or not
10.Write a C++ program to check if a prime number or not
LAB PROGRAMS – ONLINE C++
COMPILER

1. Write a C++ Program to perform different arithmetic operations

2. Prashanth was sick and writes a letter to his teacher stating that he is suffering from fever
with a temperature of 100.5 F, His teacher asks him to mention the temperature in Celsius.
Can you please help Prashanth ?

3. Greet your friend based on the Time input from the him/her.[using conditional statement]

4. Get the dateofbirth of your friend and find his lucky number (sum of all digits in the dob)
10
5
5. I have a magic number – 7365 , can you find the digit with highest value

6. Can you find the place value of the numbers 4 in 234, 456, 645

04/09/2024 Object Oriented Design and


Additional C++ operates

<< Insertion Operator


>> Extraction Operator
:: Scope Resolution Operator
: : * Pointer-to-member declaration
->* Pointer-to-member Operator
.* Pointer-to-member Operator
delete Memory Release Operator
endl Line Feed Operator
new Memory Allocation Operator
setw Field Width Operator
Pointers
Pointers

A pointer is a variable used to store the address of a memory cell.


We can use the pointer to reference this memory cell

Memory address: 1020 1024 1032

… … 100 … 1024 …
intege
pointer
r
Pointer Types

Pointer
C++ has pointer types for each type of object
Pointers to int objects
Pointers to char objects
Pointers to user-defined objects
(e.g., Student, Complex)
Even pointers to pointers
Pointers to pointers to int objects
Pointer Variable

Declaration of Pointer variables


type* pointer_name;
//or
type *pointer_name;
where type is the type of data pointed to (e.g. int, char, double)
Examples:
int *n;
RationalNumber *r;
int **p; // pointer to pointer
Address Operator &

The "address of " operator (&) gives the memory address of the
variable
Usage: &variable_name

Memory address: 1020 1024

… … 100 … … …
a
int a = 100;
//get the value,
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024
Address Operator &

Memory address: 1020 1024 1032

… 88 100 … … …
a b
#include <iostream>
using namespace std;
Result is:
void main(){ The address of a is: 1020
int a, b; The address of b is: 1024
a = 88;
b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
}
Pointer Variables

Memory address: 1020 1024 1032

… 88 100 … 1024 …
a p
int a = 100; Result is:
int *p = &a; 100 1024
cout << a << " " << &a <<endl; 1024 1032
cout << p << " " << &p <<endl;
The value of pointer p is the address of variable a
A pointer is also a variable, so it has its own memory address
Dereferencing Operator *

We can access to the value stored in the variable pointed to by


using the dereferencing operator (*),

Memory address: 1020 1024 1032

… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
Pointer Example

#include <iostream>
using namespace std;
int main (){
int value1 = 5, value2 = 15;
int *p1, *p2;
p1 = &value1; // p1 = address of value1
p2 = &value2; // p2 = address of value2
*p1 = 10; // value pointed to by p1=10
*p2 = *p1; // value pointed to by p2= value // pointed to by
p1
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "value1==" << value1 << "/ value2==" << value2;
return 0;
}
Pointer with array name Example

#include <iostream>
using namespace std;

void main (){


int a[5];
cout << "Address of a[0]: " << &a[0] << endl
<< "Name as pointer: " << a << endl;
}

Result:
Address of a[0]: 0x0065FDE4
Name as pointer: 0x0065FDE4
Reference Variables

A reference is an additional name to


an existing memory location . A reference main()
variable serves as an name for an object {
int m = 10;
int &j = m; // j is a reference variable
cout << “value of m = “ << m << endl;
//print 10
j = 18;
cout << “value of m = “ << m << endl;
// print 18
}
Pointer to Pointer

What is the output?


58 , 234560,
234560
Structure vs Class in C++
In C++, a structure is the same as a class except for a few differences.
The most important of them is security.
A Structure is not secure and cannot hide its implementation details from the end user
while a class is secure and can hide its programming and designing details.
Members of a class are private by default and members of a struct are public by default.

// Program 1 // Program 2
#include <stdio.h> #include <stdio.h>

class Test { struct Test {


int x; // x is private int x; // x is public
}; };
int main() int main()
{ {
Test t; Test t;
t.x = 20; // compiler error because x is private t.x = 20; // works fine because x is public
getchar(); getchar();
return 0; return 0;
} }
Namespace std
namespace A In programming, we cannot have
{ variables, functions, etc with the same
int x = 5;
void printX()
name. So to avoid those conflicts we use
{ namespaces.
// function statements goes here
cout<<x<<endl;
}
}
int main()
namespace B
{ {
int x=10; A::printX() ;
void printX() B::printX();
{
// function statementsgoes here return 0;
cout<<x<<endl;
}
}
}
“using namespace std” means we use the namespace named std.
“std” is an abbreviation for standard.
So all the things with in “std” namespace are used.
If we don’t want to use this line of code, we can use the things in
this namespace like this. std::cout, std::endl.
If this namespace is not used, then computer finds for the cout, cin
and endl etc.. Computer cannot identify those and therefore it
throws errors.
The functionalities like cout, cin are defined in the namepace std
present in the header file - iostream
Characteristics of Object-Oriented Languages

• Object Class
• Data Abstraction and Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing

04/09/2024 Object Oriented


123
Design and
CLASS
• A class is a blueprint, or prototype which defines and describes the member attributes
and member functions.

A class is a three-part containing the class name, data attributes (variables) and the member
functions.
• Class Name
• Member attributes (variables)
• Member functions
Main Points
12 • The Class name is an identifier, which is the user-defined data type name.
4 • The member attributes hold data just like variables which can be accessed by the member
attributes only via particular class/objects.
• The member functions may have productive behaviors or may be designed to do some
operations with member attributes just like normal functions, but the member functions can
be accessed only via the corresponding class or its objects.

04/09/2024 Object Oriented Design and


Object / Instance

• An object is an instance of a class.


• A class is only a prototype. Which doesn't have any memory for storing value(which is
exceptional for static members). Objects are the instances of a class.
•The member variables hold the data and the member functions do operations based on these
objects of the class.

•Most of the OOPS concepts are implemented based on classes. Some of them are
Inheritance, Polymorphism, Abstraction, Encapsulation.

12
5

04/09/2024 Object Oriented Design and


General Syntax of Class
class Classname {
access_specifier:
member_varibales;
member_functions;
}object1, object2;
where 'Classname' is an identifier of the class, 'object1' and
'object2' are objects of this class (which is an optional
declaration, we may be declared in the main function).
ARRAY
An array is a collection of elements of the same type placed in contiguous memory
locations that can be individually referenced by using an index to a unique identifier.

Five values of type int can be declared as an array without having to declare five
different variables (each with its own identifier).

For example, a five element integer array foo may be logically represented as;
type name [elements];
where type is a valid type (such as int, float ...), name is a valid identifier and the
elements field (which is always enclosed in square brackets []), specifies the size of
the array.

Thus, the student array, with five elements of type int, can be declared as:
int student [7];
Character Data Types
Data Type
Description Size Typical Range
(Keywords)
Any single character. It may include a letter, a -128 to 127 or 0 to
char 1 byte
digit, a punctuation mark, or a space. 255

signed char Signed character. 1 byte -128 to 127

unsigned char Unsigned character. 1 byte 0 to 255

2 or 4
wchar_t Wide character. 1 wide character
bytes
Integer Data Types
Data Type Description Size Typical Range
(Keywords)
-2147483648 to
int Integer. 4 bytes
2147483647
Signed integer. Values may be -2147483648 to
signed int 4 bytes
negative, positive, or zero. 2147483647

Unsigned integer. Values are always


unsigned int 4 bytes 0 to 4294967295
positive or zero. Never negative.
short Short integer. 2 bytes -32768 to 32767
Signed short integer. Values may be
signed short 2 bytes -32768 to 32767
negative, positive, or zero.

Unsigned short integer. Values are


unsigned short 2 bytes 0 to 65535
always positive or zero. Never negative.

-2147483648 to
long Long integer. 4 bytes
2147483647
Signed long integer. Values may be -2147483648 to
signed long 4 bytes
negative, positive, or zero. 2147483647

Unsigned long integer. Values are


unsigned long 4 bytes 0 to 4294967295
always positive or zero. Never negative.
Floating Point Data Types
Data Type Description Size Typical Range
(Keywords)

Floating point number. There is


no fixed number of digits before +/- 3.4e +/- 38 (~7
float 4 bytes
or after the decimal point. digits)

Double precision floating point


+/- 1.7e +/- 308 (~15
double number. More accurate 8 bytes
digits)
compared to float.

Long double precision floating +/- 1.7e +/- 308 (~15


long double 8 bytes
point number. digits)
Boolean Data Types

Data Type
Description Size Typical Range
(Keywords)

Boolean value. It can only take one of


bool two values: true or false. 1 byte true or false
String

n The string Type


n a programmer-defined
type
n requires #include <string>
n A string is a sequence of characters
"Hi Mom"
"We're Number 1!"
"75607"
C++ program using data types

n // C++ program to sizes of data types n cout << "Size of unsigned long int : "
n #include<iostream> << sizeof(unsigned int) << " bytes" <<
n using namespace std; endl;
n int main() n cout << "Size of float : " <<
sizeof(float) << " bytes" <<endl;
n {
n cout << "Size of double : " <<
n cout << "Size of char : " << sizeof(double) << " bytes" << endl;
sizeof(char) << " byte" << endl;
n cout << "Size of wchar_t : " <<
n cout << "Size of int : " << sizeof(wchar_t) << " bytes" <<endl;
sizeof(int)
<< " bytes" << endl; n return 0;
n
cout << "Size of short int : " << n }
n sizeof(short int) << " bytes" << endl;
cout << "Size of long int : " <<
n sizeof(long int) << " bytes" << endl;
cout << "Size of signed long int : " <<
sizeof(signed long int) << " bytes" <<
endl;
Variables

Each memory
location in a
computer has an
address.

Although the
addresses are used
Variables are by the computer
Since a variable
names for internally, it is very
holds a data item, it
has a type. memory inconvenient for the
locations. programmer to use
addresses.

A programmer can
use a variable,
such as score, to
store the integer
value of a score
received in a test.
Rules for naming variables in C++

A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9,
and the underscore character.

The first character must be a letter or underscore.

Blank spaces cannot be used in variable names.

Special characters like #, $ are not allowed.

C++ keywords cannot be used as variable names.

Variable names are case-sensitive.

A variable name can be consisting of 31 characters only if we declare a variable more


than one characters compiler will ignore after 31 characters.

Variable type can be bool, char, int, float, double, void or wchar_t.
Declarations

n Constants and variables must be declared before they can be


used.

• A constant declaration specifies the type, the name and the


value of the constant.
• A variable declaration specifies the type, the name and
possibly the initial value of the variable.

n When you declare a constant or a variable, the compiler:


1. Reserves a memory location in which to store the value of
the constant or variable.
2. Associates the name of the constant or variable with the
memory location.
Variable declarations

n Variables are used to store values that can be changed


during the program execution.
n A variable is best thought of as a container for a value.
n Syntax:
n < type > < identifier >;
n < type > < identifier > = <
expression>;

n int sum; //single declaration


Examples:
n float p,q,r; //multiple declaration
n char answer = 'y';
n double temperature = -3.14;
Variable declarations
• A variable has a type and it can contain only values of that
type.
n For example, a variable of the type int can only
hold integer values.
• Variables are not automatically initialized.
n For example, after declaration
n int sum;
n the value of the variable sum can
be anything (garbage).

n Thus, it is good practice to initialize variables when they are


declared.
n Once a value has been placed in a variable it stays there until the
program deliberately alters it.
Variable declarations

n int i; // declared but not initialised

n char c;

n int i, j, k; // Multiple declaration

n int i=0; // declaration

n i = 10; // initialization

n int i=10; //initialization and declaration in same step

n int i=10, j=11;


VARIABLE DECLARATION

THREE TYPES:
1.GENERAL
1.STATIC
2.CONSTANT
Variable Declaration
n #include <iostream>
n using namespace std;
n int main ()
n {
n // Variable definition:
n int a, b;
n int c;
n float f;
n // actual initialization
n a = 10;
n b = 20;
n c = a + b;
n f = 70.0/3.0;
n cout<<c<<endl<<f;
Static
Static
Static Variables inside Function
Example : without static keyword
Output (without using static
keyword)
Example:with using Static Keyword
Output (with using static keyword)
Constants
Constants

Constants
refer to as
fixed values, Constant
unlike must have to It is
variables be initialized considered
whose value at the time best practice
Constants are Constants can
can be of creating to define
also called be any of the
altered, it, and new constants
literals. data types.
constants - values using only
as the name cannot be upper-case
implies does assigned names.
not change, later to it.
they remain
constant.
Constant Definition in C++

By using const keyword By using #define preprocessor


Constant Definition by using const keyword
Syntax:
const type constant_name;

Example:
#include <iostream>
using namespace std;
int main()
{
const int SIDE = 50;
int area;
area = SIDE*SIDE;
cout<<"The area of the square with side: " << SIDE <<" is: " << area <<
endl;
return 0;
}
Constant Definition by using #define preprocessor
Syntax:
#define constant_name;

Example:
#include <iostream>
using namespace std;
#define VAL1 20
#define VAL2 6
#define Newline '\n’
int main()
{
int tot;
tot = VAL1 *
VAL2;
cout << tot;
cout << Newline;
Special Character Constant
Dereferencing Operator *

n We can access to the value stored in the variable


pointed to by using the dereferencing operator (*),

Memory address: 1020 1024 1032

… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
Pointer Sample
int A = 3; Q = &B;
int B; if (P == Q)
int *P = &A; printf(“1\
int *Q = P; n”); if (Q ==
int *R = R)
&B; printf(“2\
n”); if (*P ==
printf(“Enter value:“); *Q)
scanf(“%d”,R); printf(“3\n”);
printf(“%d %d\n”,A,B); if (*Q ==
printf(“%d %d %d\n”, *R) printf(“4\
*P,*Q,*R); n”); if (*P ==
*R) printf(“5\
n”);
Pointer Example

n #include <iostream>
n using namespace std;
n int main (){
n int value1 = 5, value2 = 15;
n int *p1, *p2;
n p1 = &value1; // p1 =
n address of value1
n p2
*p1==&value2;
10; // //value
p2 = pointed to by p1=10
n
address
*p2 = *p1;of value2
// value pointed to by p2= value // pointed to
by p1
n p1 = p2; // p1 = p2 (pointer value copied)
n *p1 = 20; // value pointed to by p1 = 20
n cout << "value1==" << value1 << "/ value2==" << value2;
n return 0;
n
Pointer with array name
Example
#include <iostream>
using namespace std;

void main (){


int a[5];
cout <<
"Address
of a[0]: "
<< &a[0]
<< endl
<< "Name
as
pointer:
" << a
<<
endl;
}
Reference Variables

A reference is an additional name to an


main()
existing memory location . A
{
reference variable serves as an int m = 10;
name for an object int &j = m; // j is a reference
variable
cout << “value of m = “ << m <<
endl;
//print 10
j = 18;
cout << “value of m = “ << m <<
endl;
// print 18
}
Pointers Example 1
#include <iostream>
Value of var variable: 20
using namespace std; Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
int main ()
{
int var = // actual variable declaration.
int
20; *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;
}
16
1
Pointer with array name Example

#include <iostream>
using namespace std;

void main ()
{
int a[5];
cout << "Address of a[0]: " << &a[0] << endl
<< "Name as pointer: " << a << endl;
}

Result:
Address of a[0]: 0x0065FDE4
Name as pointer: 0x0065FDE4
Pointers Detail
Concept Description

C++ Nu C++ supports null pointer, which is a constant with a value of zero defined
l l Pointers in several standard libraries.

C+ + p There are four arithmetic operators that can be used on pointers: ++, --, +,
oin ter -
arithmetic
C++ There is a close relationship between pointers and arrays. Let us check how?
pointers vs
arrays
C+ + You can define arrays to hold a number of pointers.
array of
pointers
C++ C++ allows you to have pointer on a pointer and so on.
pointer to
pointer
Passing Passing an argument by reference or by address both enable the
pointers to passed argument to be changed in the calling function by the
functions called function.
Return C++ allows a function to return a pointer to local variable, static variable
poi nte r and dynamically allocated memory as well.
from
functions 16
3
Null Pointer
• It is always a good practice to assign the pointer NULL to a pointer
variable in case you do not have exact address to be assigned. This is
done at the time of variable declaration. A pointer that is assigned NULL
is called a null pointer.

#include <iostream> The value of ptr is 0

using namespace std;

int main ()
{
int *ptr = NULL;

cout << "The value of ptr is " << ptr ;

return 0;
}

16
4
C++ Pointer arithmetic
#include <iostream> Address of var[0] = 0xbfa088b0
Value of var[0] = 10
using namespace std; Address of var[1] = 0xbfa088b4
const int MAX = 3; Value of var[1] = 100
Address of var[2] = 0xbfa088b8
int main () Value of var[2] = 200
{
int var[MAX] =
{10, 100, 200};
int *ptr;

// let us have array address in pointer.


ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;
// point to the next location
ptr++;
}
return 0;
} 16
5
C++ pointers vs arrays
#include <iostream> Address of var[0] = 0xbfa088b0
Value of var[0] = 10
using namespace std; Address of var[1] = 0xbfa088b4
const int MAX = 3; Value of var[1] = 100
Address of var[2] = 0xbfa088b8
int main ()
{ Value of var[2] = 200
int var[MAX] =
{10, 100, 200};
int *ptr;

// let us have array address in pointer.


ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;
// point to the next location
ptr++;
}
return 0;
} 16
6
C++ array of pointers
#include <iostream> Value of var[0] = 10
Value of var[1] = 100
using namespace std; Value of var[2] =
const int MAX = 3; 200
int main ()
{
int var[MAX] =
{10, 100, 200};
int *ptr[MAX];

for (int i = 0; i <


MAX; i++)
{
ptr[i] = &var[i]; //
assign the
address of integer.
}
for (int i = 0; i <
MAX; i++)
{
cout << "Value of var[" << i << "] = ";
cout << *ptr[i] << endl;
} 16
7
C++ pointer to pointer
#include <iostream> Value of var :3000
Value available at *ptr :3000
using namespace std; Value available at **pptr :3000

int main ()
{
int var;
int *ptr;
int
**pptr;
var =
3000;

// take the address of var


ptr = &var;

// take the address of ptr using address of operator &


pptr = &ptr;

// take the value using pptr


cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;

return 0; 16
8
Type Conversions

9.114
Type Casting/ Type Conversion
A type cast is basically a conversion from one type to another.

Done by the compiler on its own, without any external


trigger from the user.

Generally takes place when in an expression more than


one data type is present.

Implicit Type
Conversion Also In such condition type conversion (type promotion)
known as ‘automatic takes place to avoid lose of data.
type conversion’.

All the data types of the variables are upgraded to the data
type of the variable with largest data type.

It is possible for implicit conversions to lose information,


signs can be lost (when signed is implicitly converted to
unsigned), and overflow can occur (when long long is
implicitly converted to float).
C++ program to demonstrate implicit type casting

#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x char
y = 'a'; // character c

// y implicitly converted to
int. ASCII
// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y <<
endl
<< "z = " << z <<
endl;

return 0;
Type Casting/ Type Conversion

This is done by explicitly


defining the required type in
front of the expression in
parenthesis.

Converting by This can be also considered as


assignment forceful casting.

Syntax: (type) expression


Explicit Type where type indicates the data
Conversion: type to which the final result is
converted.

A Cast operator is an unary


Conversion using operator which forces one
Cast operator data type to be converted
into another data type.

9.117
C++ program to demonstrate explicit type casting

#include <iostream>
using namespace std;
int main()
{
double x =
1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;


}
Features: Classes and Objects

9.119
Classes in C++

Class Object

A collection of
related variables and Instances of the
functions into a class are called
single structure objects.

The variables and


A user-defined
complex data type functions in the
with its own definition of the
operations class are called
members.

175
Class Scope

Outside a
Class data
Within a class's scope,
members and Use dot (.)
member class's scope, class members Use arrow (->)
notation for
functions class members are referenced object and for pointer to
belong to that are references through one references. the object
class's by name. of the handles
scope. on an object.

E.g: c.x , cpt -> x

176
Implementation of a Class

Class declaration Class definition

Declarations of data Not usually placed


members in class declaration

Definitions placed
outside the class
Prototypes
declaration must tell
(declarations) of compiler where the
function members corresponding
declaration/prototype is
syntax
Access Functions and Utility Functions

Utility functions Access functions

Private functions Public functions For a data


Not intended to be
that support the that structure, it could
used directly by
operation of public read/display call the isEmpty
clients
functions data or check function
conditions
Defining Member Function of Class

Member functions can be


defined in two ways:

Inside the class Outside the class


Syntax: for object creation and to
access member functions from
class

To create object:
classname objectname;

To access member function from class:


objectname.functionname();
Defining Member Function of Class: Inside the class

You can define Functions inside the class as shown in previous slides.

Member functions defined inside a class this way are created as inline functions by default.

It is also possible to declare a function within a class but define it elsewhere.

Functions defined outside the class are not normally inline.

When we define a function outside the class we cannot reference them (directly) outside of the
class.

In order to reference these, we use the scope resolution operator, :: (double colon).
Defining Member Function of Class: Outside the class

A large program may contain many member functions.

For the clarity of the code, member functions can be defined outside the class.

To do so, member function should be declared inside the class(function prototype


should be inside the class).

Then, the function definition can be defined using scope resolution operator ::.

When we define a function outside the class we cannot reference them (directly)
outside of the class.

In order to reference these, we use the scope resolution operator, :: (double


colon).

In this example, we are defining function setRadius outside the class:

void Circle :: setRadius(double r) { radius = r; }


Syntax to define functions inside
the class and outside the class:
Function definition inside the class:
Access Specifier:datatype functionname(arguments)
{
Function definition
}

Function definition outside the class:


Datatype classname::functionname(arguments)
{
Function definition

}
Object Declaration

Once a class is defined, you can declare objects of that


type.

The syntax for declaring a object is the same as that for


declaring any other variable.

The following statements declare two objects of type


circle:
• Circle c1, c2;

Circle is class and c1 and c2 are the objects.

Once the class is defined you can define any number of


objects.
Object Declaration: Accessing Class Members

Once an object of a class is declared, it can access the


public members of the class using ( . ) dot membership
operator.

c1.setRadius(2.5);
Defining Class

Example

class Circle
{
private: double radius;
public: void setRadius(double r)
{ radius = r; } double
getArea()
{ return 3.14 * radius *
radius; }
};
Example
#include <iostream>
using namespace std;
class Box
{ public:
double length; // Length of a box double
breadth; // Breadth of a box
double height; // Height of a box
};
int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type
Box
double volume = 0.0; // Store the
volume of a box here
// box 1 specification
Box1.height = 4.0;
Box1.length = 6.0;
Box1.breadth = 3.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth =
12.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
Example for memberfunction inside the
class
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

double getVolume(void)
{
return length * breadth * height;
}
};
Example program for member function outside the class:

#include <iostream>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

// Member functions declaration


double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};

// Member functions definitions


double Box::getVolume(void) {
return length * breadth * height;
}
Example continuing…
void Box::setLength( double len ) {
length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}

// Main function for the program


int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
Example Continuing..
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

Output:
Volume of Box1: 210
Volume of Box 2: 1560
Access Specifiers
Access-specifiers in C++

Access modifiers (or access


Access modifiers are a specific part of
specifiers) are keywords in object-
programming language syntax used to
oriented languages that set the
facilitate the encapsulation of
accessibility of classes, methods, and
components
other members.

Access-specifier can be changed in any order, default is private.

194
Access-specifiers in C++

Private (default) Public Protected

Can be accessed
only by other Can be accessed Needed only when
by other parts of inheritance is
members of the
the program involved.
class.

Access-specifier can be changed in any order, default is private.

195
EXAMPLE
#include <iostream>
using namespace std;

// define a class
class Sample {

// public elements
public:
int age;

void displayAge()
{
cout << "Age =
" << age <<
endl;
}
};
Continuing example…
int main() {

// declare a class object


Sample obj1;

cout << "Enter your age:


";

// store input in age of the obj1 object


cin >> obj1.age;

// call class function


obj1.displayAge();

return 0;
}
Access Specifiers Example 1
#include <iostream> // Main function for the program
using namespace std;
int main( )
class Line {
{ Line line;
public:
double length; // set line length
void setLength( double len ); line.setLength(6.0);
double getLength( void ); cout << "Length of
}; line : " <<
line.getLength()
double Line::getLength(void) <<endl;
{
return length ; // set line length
} without member
function
void Line::setLength( double len
) line.length = 10.0; // OK: because length is public
{ Length
cout <<of line : 6
"Length of line : " << line.length <<endl;
length = len; Length of line : 10
return 0;
} }
Access Specifiers Example 2
#include <iostream>
// Main function for the program
using namespace std; int main( )
{
class Box Box box;
{
public: // set box length without member function
double length; box.length = 10.0; // OK: because length is public
void setWidth( double wid ); cout << "Length of box : " << box.length <<endl;
double getWidth( void );
// set box width without member function
private: // box.width = 10.0; // Error: because width is private
double width; box.setWidth(10.0); // Use member function to set it.
}; cout << "Width of box : " << box.getWidth() <<endl;

// Member functions definitions return 0;


double Box::getWidth(void) }
{
return width ;
}
Length of box : 10
void Box::setWidth( double Width of box : 10
wid )
{
width = wid;
}
Access Specifiers Example 3
#include <iostream> void SmallBox::setSmallWidth( double wid )
using namespace std; {
width = wid;
class Box }
{
protected: // Main function for the program
double width; int main( )
}; {
SmallBox box;
class
SmallBox:Box // set box width using member function
{ box.setSmallWidth(5.0);
public: cout << "Width of box : "<<
void setSmallWidth( double wid ); box.getSmallWidth();
double getSmallWidth( void );
}; return 0;
}
// Member functions of child class
double SmallBox::getSmallWidth(void) Width of box : 5
{
return width ;
}
METHODS (FUNCTIONS)
Example: Inside
Example:Outside
We can also add parameters
CONSTRUCTOR
A constructor is a particular member function having the same name as the
class name. It calls automatically whenever the object of the class is created.

SYNTAX:
class class_name
{
……….
public
class_name ([parameter list]) //CONSTRUCTOR
{
……………….
}
};
TYPES OF CONSTRUCTORS:
•Default constructor:

•Dynamic constructor

•Parameterized constructor

•Copy constructor
UML
UML Diagrams stands for Unified Modeling Language.

It is a standard which is mainly used for creating object-


oriented, meaningful documentation models for any software
system present in the real world.

It provides us a way to develop rich models that describe the


working of any software/hardware systems.

UML serves a great way of creating professional


documentation which is a necessary part of any project
development.

UML is an essential part of creating an object-oriented


design of systems.
UML DIAGRAMS

UML Diagrams are the output of the Unified Modeling Language.

It is a pictorial representation of classes, objects, and relationships


between them.

UML diagram is a model that describes a part of a system.

It is used to define the functionality or a design of a system.

A diagram must be clear and concise so that the viewer will readily
understand it.
THREE CATEGORIES OF UML
DIAGRAMS

Structural diagram

Behavioral diagram

Interaction diagram
STRUCTURAL DIAGRAM

Structural diagrams are used to represent a static view of a system.


It represents a part of a system that makes up the structure of a system.
A structural diagram shows various objects within the system.

TYPES OF STRUCTURAL DIAGRAM:


Class diagram
Object diagram
Package diagram
Component diagram
Deployment diagram
BEHAVIORAL DIAGRAMS
Any real-world system can be represented in either a static form or a dynamic
form. A system is said to be complete if it is expressed in both the static and
dynamic ways.

The behavioral diagram represents the functioning of a system.

UML diagrams that deals with the static part of a system are called structural
diagrams.

UML diagrams that deals with the moving or dynamic parts of the system are
called behavioral diagrams.

Following are the various behavioral diagrams in UML:

Activity diagram
Use case diagram
State machine diagram
INTERACTION DIAGRAMS

Interaction diagram is nothing but a subset of behavioral diagrams.

It is used to visualize the flow between various use case elements of a system.

Interaction diagrams are used to show an interaction between two entities and
how data flows within them.

Following are the various interaction diagrams in UML:

Timing diagram
Sequence diagram
Collaboration diagram
CLASS DIAGRAM:

The class diagram depicts a static view of an application.

It represents the types of objects residing in the system and the relationships
between them.

A class consists of its objects, and also it may inherit from other classes.

A class diagram is used to visualize, describe, document various different aspects


of the system, and also construct executable software code.

It shows the attributes, classes, functions, and relationships to give an overview


of the software system. It constitutes class names, attributes, and functions in a
separate compartment that helps in software development.

Since it is a collection of classes, interfaces, associations, collaborations, and


constraints, it is termed as a structural diagram.
PURPOSE OF CLASS
DIAGRAMS
The main purpose of class diagrams is to build a static view of an application.

It is the only diagram that is widely used for construction, and it can be mapped with
object-oriented languages.

It is one of the most popular UML diagrams.

Following are the purpose of class diagrams given below:

It analyses and designs a static view of an application.


It describes the major responsibilities of a system.
It is a base for component and deployment diagrams.
It incorporates forward and reverse engineering.
BENEFITS OF CLASS
DIAGRAMS
It can represent the object model for complex systems.

It reduces the maintenance time by providing an overview of how an application


is structured before coding.

It provides a general schematic of an application for better understanding.

It represents a detailed chart by highlighting the desired code, which is to be


programmed.

It is helpful for the stakeholders and the developers.


COMPONENTS OF CLASS
DIAGRAM
UPPERSECTION OF CLASS
DIAGRAM:

Upper Section: The upper section encompasses the name of the class.

A class is a representation of similar objects that shares the same


relationships, attributes, operations, and semantics.

Some of the following rules that should be taken into account while
representing a class are given below:
Capitalize the initial letter of the class name.
Place the class name in the center of the upper section.
A class name must be written in bold format.
The name of the abstract class should be written in italics format.
MIDDLE SECTION OF CLASS
DIAGRAM

Middle Section: The middle section constitutes the attributes, which describe the
quality of the class.

The attributes have the following characteristics:


The attributes are written along with its visibility factors, which are public (+),
private (-), protected (#), and package (~).
The accessibility of an attribute class is illustrated by the visibility factors.
A meaningful name should be assigned to the attribute, which will explain its
usage inside the class.
LOWER SECTION OF CLASS
DIAGRAM

Lower Section: The lower section contain methods or operations.

The methods are represented in the form of a list, where each method is
written in a single line.

It demonstrates how a class interacts with data.


UML RELATIONSHIPS ;
THREE TYPES

1. Dependency

2. Generalization

3. Association
DEPENDENCY

Dependency: A dependency is a semantic relationship between two or more classes


where a change in one class cause changes in another class. It forms a weaker
relationship.

In the following example, Student_Name is dependent on the Student_Id.


GENERALIZATION

Generalization: A generalization is a relationship between a parent class


(superclass) and a child class (subclass).
In this, the child class is inherited from the parent class.
For example, The Current Account, Saving Account, and Credit Account are
the generalized form of Bank Account.
GENERALIZATION
Shape

Separate Target Style

Polygon Ellipse Spline . ..

Shape
Shared Target Style

...
Polygon Ellipse Spline
GENERALIZATION

• hierarchies drawn top-down


• arrows point upward to parent

• line/arrow styles indicate whether parent is a(n):


– class:
solid line, black arrow
– abstract class:
solid line, white arrow
– interface:
dashed line, white arrow
Association

Association: It describes a static or physical connection between two or


more objects.
It depicts how many objects are there in the relationship.
For example, a department is associated with the college.
THREE TYPES OF
ASSOCIATIONS
1.Multiplicity

2.Aggregation

3.Composition
MULTIPLICITY

Multiplicity: It defines a specific range of allowable instances of


attributes. In case if a range is not specified, one is considered as a
default multiplicity.

For example, multiple patients are admitted to one hospital.


AGGREGATION

Aggregation: An aggregation is a subset of association, which represents has a


relationship.
It is more specific then association. It defines a part-whole or part-of
relationship.
In this kind of relationship, the child class can exist independently of its
parent class.

The company encompasses a number of employees, and even if one employee


resigns, the company still exists.
COMPOSITION

Composition: The composition is a subset of aggregation.


It portrays the dependency between the parent and its child, which means
if one part is deleted, then the other part also gets discarded. It represents a
whole-part relationship.

A contact book consists of multiple contacts, and if you delete the contact
book, all the contacts will be lost.
NOTATIONS
EXAMPLE
EXAMPLE FOR ASSOCIATIONS AND
MULTIPLICITY
LABELLING ASSOCIATION
MULTIPLICITY OF ASSOCIATIONS
MULTIPLICITY OF
ASSOCIATIONS
MULTIPLICITY OF
ASSOCIATIONS
Many-to-many
A secretary can work for many managers
A manager can have many secretaries
Secretaries can work in pools
Managers can have a group of secretaries
Some managers might have zero secretaries.
Is it possible for a secretary to have, perhaps temporarily, zero managers?
ABSTRACT CLASS

Abstract Classes
An abstract class is a class that is designed to be specifically used as a
base class.

The purpose of an abstract class (often referred to as an ABC) is to


provide an appropriate base class from which other classes can inherit.

Abstract classes cannot be used to instantiate objects and serves only as


an interface.

Attempting to instantiate an object of an abstract class causes a


compilation error.

The notation of the abstract class is similar to that of class; the only
difference is that the name of the class is written in italics.
ABSTRACT CLASS

Let us assume that we have an abstract class named displacement with a


method declared inside it, and that method will be called as a drive ().
Now, this abstract class method can be implemented by any object, for
example, car, bike, scooter, cycle, etc.
HOW TO DRAW CLASS DIAGRAM?

The class diagram is used most widely to construct software applications. It


represents a static view of the system and all the major aspects of an application. A
collection of class diagrams as a whole represents a system.

Some key points that are needed to keep in mind while drawing a class diagram are
given below:

1. To describe a complete aspect of the system, giving a meaningful name to the


class diagram is suggested.
2. The objects and their relationships should be acknowledged in advance.
3. The attributes and methods (responsibilities) of each class must be known.
4. A minimum number of desired properties should be specified as more unwanted
properties will lead to a complex diagram.
5. Notes can be used as and when required by the developer to describe the aspects
of a diagram.
6. The diagrams should be redrawn and reworked as many times to make it correct
before producing their final version.
CLASS DIAGRAM EXAMPLE
Class diagram pros/cons
• Class diagrams are great for:
– discovering related data and attributes
– getting a quick picture of the important entities in a system
– seeing whether you have too few/many classes
– seeing whether the relationships between objects are too
complex, too many in number, simple enough, etc.
– spotting dependencies between one class/object and another

• Not so great for:


– discovering algorithmic (not data-driven) behavior
– finding the flow of steps for objects to solve a given problem
– understanding the app's overall control flow (event-driven? web-
based? sequential?etc.)
Use Cases

What is a Use Case


 A formal way of representing how a business system interacts with
its environment
 Describes the system's actions from a the point of view of a user
 A scenario-based technique in the UML
Use case examples

9.
Use case examples, 2

9.
Use Case Descriptions

• actors - something with a behavior or role, e.g., a person, another


system, organization.
• scenario - a specific sequence of actions and interactions between
actors and the system, a.k.a. a use case instance
• use case - a collection of related success and failure scenarios,
describing actors using the system to support a goal.
1. Component - Use Cases

A use case is a summary of scenarios for a single task or goal.

An actor is who or what initiates the events involved in the task of the use
case. Actors are simply roles that people or objects play.
Use Case
Each use case in a use case diagram describes one
and only one function in which users interact with
the system

May contain several “paths” that a user can take while


interacting with the system
Each path is referred to as a scenario
2. Component - Actor

 Include all user roles that interact with the system


Include system components only if they responsible for
initiating/triggering a use case.
• -- For example, a timer that triggers sending of an e-mail
reminder
primary actor- a user whose goals are fulfilled by the system
importance: define user goals
supporting actor - provides a service (e.g., info) to the
system
importance: clarify external interfaces and protocols
Component - Actors

External objects that produce/consume data:


Must serve as sources and destinations for data
Must be external to the system .
It can be a:
Human, Machines , Organizations
Peripheral device (hardware)
External system or subsystem
Time or time-based event
Represented by stick figure
3. Component- Relationships

Relationships
Represent communication between actor and use case
Depicted by line or double-headed arrow line
Also called association relationship
Linking Use Cases

• Association relationships communication between an actor and a use case;


Represented by a solid line.
• Generalization relationships
relationship between one general use case and a special use case (used for defining
special alternatives)
Represented by a line with a triangular arrow head toward the parent use case.

• Include relationships
• One use case (base) includes the functionality of
another (inclusion case)
• Supports re-use of functionality
• Extend relationships
• One use case (extension) extends the behavior of
another (base)
Generalization

The child use case inherits the behavior


and meaning of the parent use case.
The child may add to or override the
behavior of its parent

The actor Order Registry Clerk can


instantiate the general use case Place
Order.
Place Order can also be specialized by the
use cases Phone Order or Internet Order.
include

The base use case explicitly incorporates the behavior of another use case at a
location specified in the base.

The included use case never stands alone. It only occurs as a part of some
larger base that includes it.
Example:Login UC includes User Authentication UC);
to Authorize Car Loan (standard use case), a clerk must run Check Client’s Credit
History (include use case)
extend

The base use case implicitly incorporates the behavior of another use case at
certain points called extension points.
The base use case may stand alone, but under certain conditions its
behavior may be extended by the behavior of another use case.
How to create use case
diagram
1. List main system functions (use cases) in a column:
– think of business events demanding system’s response
– users’ goals/needs to be accomplished via the system
– Create, Read, Update, Delete (CRUD) data tasks
– Naming use cases
– user’s needs usually can be translated in data tasks
2. Draw ovals around the function labels
3. Draw system boundary
4. Draw actors and connect them with use cases (if more intuitive, this can be
done as step 2)
5. Specify include and extend relationships between use cases (yes, at the end -
not before, as this may pull you into process thinking, which does not apply in
UC diagramming)
Use-Case Diagram(Appointment system)
Use-Case Diagrams
Health Care Example - Together
Online Shopping Website – Basic Use case
ATM USE CASE

You might also like