0% found this document useful (0 votes)
28 views

Unit 1 CPP

The document discusses object-oriented programming and C++. It covers topics like features of OOP, comparison with procedural programming, OOP languages, building blocks of C++, features of C++, merits of OOP, and input/output operations in C++.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Unit 1 CPP

The document discusses object-oriented programming and C++. It covers topics like features of OOP, comparison with procedural programming, OOP languages, building blocks of C++, features of C++, merits of OOP, and input/output operations in C++.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 88

Unit I

• Object-Oriented Programming - Features of C++ - I/O


Operations, Data Types, Variables-Static, Constants-
Pointers-Type Conversions – Conditional and looping
statements – Arrays - C++ 11 features - Class and Objects,
Abstraction and Encapsulation, Access Specifier, Methods-
UML Diagrams Introduction – Use Case Diagram - Class
Diagram.
Object Oriented Programming
• Object + Data
• Object-oriented programming is based on the real world.
• Object-oriented programming is used for designing large and complex programs.
• Aim: Bind data+ functions
: Useful for collaborative development ---> groups
: Reusability, scalability and efficiency
• Collect all objects and relate each other
• Object Communicate with messages.
Procedural Programming vs. OOP
The program is divided into small parts The program is divided into small parts
called functions. called objects.

Top-down approach. Bottom-up approach.

Object-oriented programming has access


No access specifier
specifiers like private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Less secure. It is more secure.

In procedural programming, overloading is Overloading is possible in object-oriented


not possible. programming.

In procedural programming, there is no In object-oriented programming, the concept


concept of data hiding and inheritance. of data hiding and inheritance is used.

In procedural programming, the function is In object-oriented programming, data is more


more important than the data. important than function.

Procedure abstraction. Data abstraction.

Code reusability absent Code reusability present

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, java, python, C#, etc.
POP Structure & OOP Structure
OOP Languages
• Simula is the first object-oriented programming language
• Popular pure OOP languages include:
• Ruby
• Scala
• Jade
• Emerald
• Programming languages designed primarily for OOP include:
• Java
• Python
• C++
• Other programming languages that pair with OOP include:
• Visual basic .NET
• Php
• Javascript
Parameter C C++
Programming Paradigm C is a structural or procedural programming language. C is a structural as well as an object-oriented programming language.

History C was developed by scientist Dennis Ritchie in 1972 at Bell Laboratories. C was developed by Bjarne Stroustup in 1979.

Approach C follows a top-down approach C follows the bottom-up approach.


Data Types C supports built-in data types. C++ support both built-in and user-defined data types.
Access Modifier C language does not support access modifier C++ support access modifier
C++ is a secure language as it offers security features such as data hiding and
Security C does not have any security features so it can be manipulated by outsider
encapsulation
Reference Variable C does not support reference variable C++ support reference variable
Function Overloading and
C don’t supports function overloading and function overriding C++ supports function overloading and function overriding
Function Overriding
C does not support exception handling directly, it uses the function that
Exception Handling C++ directly support exception handling with the help of try – catch block
support exception handling
C is a procedural language, so code written in C are divided in separate C++ is a object oriented language, so code and divided into classes and
Program Division
blocks known as function objects
Inline Function C doesn’t support inline function C++ support inline function
Driven Type C is known as function-driven language C is known as object driven language
In C, the data and function are separated as it is a procedural In C++, the data and function are encapsulated as it is a object oriented
Data and Function
programming language programming language

C language is more suitable for low level implementation such as network C++ language is more suitable for high level implementation such as game
Application Development
driver, text editor, assembler, etc development, smartwatches, embedded systems, etc

To prevent the collision and organize the code, namespace is needed but C
Namespace C++ support the namespace
does not support that

Used By MySQL, Windows Kerne, Oracle Database, Telegram messenger, etc Google Chrome, Torque 3-D game, Microsoft Office, etc
Main Building blocks of C++

• Classes
• Objects
• Methods
• Attributes
Features of C++
Features of C++
• A class is a predefined blueprint or prototype from which objects can be created. It represents
the set of properties or methods shared by all objects of the same type.

• Object: It is a fundamental unit of the Object-oriented Programming language that represents


real-world entities.

• Encapsulation is the process of encasing data into a single unit. It is the mechanism that
connects the code and data that it manipulates.

• Data Abstraction is the property that allows only the most important details to be displayed to
the user. The user needs to be shown the trivial or non-essential units.

• Polymorphism refers to objects ability to distinguish between entities that have the same
form.

• Inheritance is the mechanism that allows one class to inherit the features (data and methods)
of another.
Other Features of C++ Programming Language

• Simple And User Friendly


• Platform Dependent
• Structured Programming Language
• Mid-Level Programming Language
• Rich Library
• Case-Sensitive
• Dynamic Memory Allocation
• Memory Management
• Multi-threading
• Powerful and Fast
• Syntax Based Language
• Integration and Extensibility
Merits of OOP
• Modularity
• Encapsulation enables objects to be self-contained, making troubleshooting and collaborative
development easier.
• Reusability
• Code can be reused through inheritance, meaning a team does not have to write the same code
multiple times.
• Productivity
• Programmers can construct new programs quicker through the use of multiple libraries and reusable
code.
• Easily upgradable and scalable
• Programmers can implement system functionalities independently.
• Interface descriptions.
• Descriptions of external systems are simple, due to message passing techniques that are used for
objects communication.
• Security.
• Using encapsulation and abstraction, complex code is hidden, software maintenance is easier
and internet protocols are protected.
• Flexibility.
• Polymorphism enables a single function to adapt to the class it is placed in.
• Different objects can also pass through the same interface
Multi-paradigm
• C++ is a multi-paradigm programming language.
• The term “Paradigm” refers to the style of programming. It includes
logic, structure, and procedure of the program.
• Generic, imperative, and object-oriented are three paradigms of C++.
• Generic programming refers to the use of a single idea to serve
several purposes.
• Imperative programming, on the other hand, refers to the use of
statements that change a program’s state.
I/O Operation

• The C++ programming language provides the several built-in


functions to display the output in formatted form.
• These built-in functions are available in the header
file iomanip.h and ios class of header file iostream.h.
• In C++, there are two ways to perform the formatted IO operations.
• Using the member functions of ios class.
• Using the special functions called manipulators defined
in iomanip.h.
Cascading of Input or Output Operators
• << operator – It can be used multiple times in the same line.
• It is called Cascading
• cout, cin can be cascaded
• For example
• cout<<“\n Enter the Name”;
• cin>> Arjun>>Lakshman;
Reading and Writing Characters and Strings
• int marks;

• cin.get(marks);//The value for marks is read

Or
• marks=cin.get();//A character is read and assigned to marks

• string name;

• cin>>name;

• string empname;

• cin.getline(empname,20);

• cout<<“\n Welcome ,”<<empname


Formatted IO using ios class memebers
• The ios class contains several member functions that are used to perform formmated IO operations.
• The ios class also contains a few format flags used to format the output. It has format flags
like showpos, showbase, oct, hex, etc. The format flags are used by the function setf( ).
• The following table provides the details of the functions of ios class used to perform formatted IO in
C++.
Function Description
width(int) Used to set the width in number of character spaces
for the immediate output data.

fill(char) Used to fill the blank spaces in output with given


character.
precision(int) Used to set the number of the decimal point to a
float value.
setf(format flags) Used to set various flags for formatting output like
showbase, showpos, oct, hex, etc.

unsetf(format flags) Used to clear the format flag setting.


Formatted IO using manipulators
The iomanip.h header file contains several special functions that are
used to perform formmated IO operations.
The following table provides the details of the special manipulator
functions used to perform formatted IO in C++.
Function Description
setw(int) Used to set the width in number of characters
for the immediate output data.

setfill(char) Used to fill the blank spaces in output with


given character.
setprecision(int) Used to set the number of digits of precision.

setbase(int) Used to set the number base.


setiosflags(format flags) Used to set the format flag.
resetiosflags(format flags) Used to clear the format flag.
Formatting with flags

• The setf() is a member function of the 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
Flag Description
endl Used to move the cursor position to a
newline.
ends Used to print a blank space (null
character).
dec Used to set the decimal flag.
oct Used to set the octal flag.
hex Used to set the hexadecimal flag.
left Used to set the left alignment flag.
right Used to set the right alignment flag.
showbase Used to set the showbase flag.
noshowbase Used to set the noshowbase flag.
showpos Used to set the showpos flag.
noshowpos Used to set the noshowpos flag.
showpoit Used to set the showpoit flag.
noshowpoint Used to set the noshowpoint flag.
Data Types
o The data type is a category of data.
o In other words, a data type is a collection of data values with similar
characteristics.
o In the C++ programming language, every variable needs to be created with a
data type.

The data type of a variable specifies the following.


•The type of value can be stored in a variable.
•The amount of memory in bytes has to be allocated for a variable.
•The range of values has to be stored in a variable.
The C++ programming language supports the following data
types.
Integer Data type
Floating-point Data type
Double Data type
Character Data type
Boolean Data type
Void Data type
Wide Character Data type
The following table describes the characteristics of each data type briefly.
Variables
Variables is a value holder in the computer program.
A variable is named memory location, where the user can store different
values of the specified data type.
In simple words, a variable is a value holder. Every variable in the
program has the following properties.
•Every variable has a name (user-specified) and an address.
•Every variable must be created with a data type.
•Every variable is allocated with a memory based on the data type of it.
•Every variable has a value.
Creating Variables
Creating a variable is nothing but declaring a variable. In C++, all the variables must be declared before they use
in the program. The general syntax for declaring a variable is as follows.

The syntax for creating a variable


data_type variable_name;

The syntax for creating a variable with an initial value


data_type variable_name = value;
In C++, multiple variables of the same data type may be declared using a single statement. In this case, all the
variables must be separated with a comma symbol.

Example statements for variable creation in C++


int a, b, c;
float x = 10.5, y;
char p = 'A', q = 'B', r = 'C';
Every declaration statement with multiple variables may contain declaration without initial value or with an
initial value or mix-up of both.are used
Types of Variables
Based on the location of variable declaration, variables are
classified into five types.

Local Variables
Global Variables
Formal Variables
Member Variables
Instance Variables
Examples

x,y is formal variable


Static Variables

a,b member variables

s is instance variables
Constants
• Constants in C++ refer to variables with fixed values that cannot be
changed.
• Once they are defined in the program, they remain constant
throughout the execution of the program.
• They are generally stored as read-only tokens in the code segment of
the memory of the program.
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 lowercase characters.
• Rule 2: No blank spaces are permitted in between the #
symbol and define the keyword. E.g. #define PI 3.14
• 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.
Arithmetic Operators
Arithmetic Operators can be classified into 2 Types:
A) Unary Operators: These operators operate or work with a single operand.
B) For example: Increment(++) and Decrement(–) Operators .

Name Symbol Description Example

Increases the integer value of int a = 5;


Increment Operator ++
the variable by one a++; // returns 6

Decreases the integer value of int a = 5;


Decrement Operator —
the variable by one a–; // returns 4
Binary Operators
These operators operate or work with two operands. For example: Addition(+), Subtraction(-), etc.

Name Symbol Description Example

int a = 3, b = 6;
Addition + Adds two operands
int c = a+b; // c = 9

int a = 9, b = 6;
Subtraction – Subtracts second operand from the first
int c = a-b; // c = 3

int a = 3, b = 6;
Multiplication * Multiplies two operands
int c = a*b; // c = 18

Divides first operand by the second int a = 12, b = 6;


Division /
operand int c = a/b; // c = 2

Returns the remainder an integer int a = 8, b = 6;


Modulo Operation %
division int c = a%b; // c = 2
Example
#include <iostream>
using namespace std;

int main()
{
int a = 8, b = 3;

// Addition operator Output


cout << "a + b = " << (a + b) << endl;

// Subtraction operator a + b = 11
cout << "a - b = " << (a - b) << endl; a-b=5
a * b = 24
// Multiplication operator a/b=2
cout << "a * b = " << (a * b) << endl; a%b=2
// Division operator
cout << "a / b = " << (a / b) << endl;

// Modulo operator
cout << "a % b = " << (a % b) << endl;

return 0;
}
Relational Operators

• These operators are used for the comparison of the values of two operands.
• For example, ‘>’ checks if one operand is greater than the other operand or not, etc. The result returns a Boolean
value, i.e., true or false.
Name Symbol Description Example

int a = 3, b = 6;
Is Equal To == Checks if both operands are equal a==b;
// returns false

int a = 3, b = 6;
Checks if first operand is greater than the second
Greater Than > a>b;
operand
// returns false

int a = 3, b = 6;
Greater Than or Equal Checks if first operand is greater than or equal to the
>= a>=b;
To second operand
// returns false

int a = 3, b = 6;
Checks if first operand is lesser than the second
Less Than < a<b;
operand
// returns true

int a = 3, b = 6;
Checks if first operand is lesser than or equal to the
Less Than or Equal To <= a<=b;
second operand
// returns true

int a = 3, b = 6;
Not Equal To != Checks if both operands are not equal a!=b;
// returns true
Example
#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Equal to operator
cout << "a == b is " << (a == b) << endl;
Output:
// Greater than operator
cout << "a > b is " << (a > b) << endl; a == b is 0
// Greater than or Equal to operator
a > b is 1
cout << "a >= b is " << (a >= b) << endl; a >= b is 1
a < b is 0
// Lesser than operator a <= b is 0
cout << "a < b is " << (a < b) << endl;
a != b is 1
// Lesser than or Equal to operator
cout << "a <= b is " << (a <= b) << endl;

// true
cout << "a != b is " << (a != b) << endl;

return 0;
}
Logical Operators

• These operators are used to combine two or more conditions or constraints or to complement the evaluation of the original
condition in consideration. The result returns a Boolean value, i.e., true or false.

Name Symbol Description Example

Returns true only if all int a = 3, b = 6;


Logical AND && the operands are true or a&&b;
non-zero // returns true

Returns true if either of int a = 3, b = 6;


Logical OR || the operands is true or a||b;
non-zero // returns true

int a = 3;
Returns true if the
Logical NOT ! !a;
operand is false or zero
// returns false
Example
#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Logical AND operator


cout << "a && b is " << (a && b) << endl;
Outut:
// Logical OR operator a && b is 1
cout << "a ! b is " << (a > b) << endl; a ! b is 1
!b is 0
// Logical NOT operator
cout << "!b is " << (!b) << endl;

return 0;
}
• These operators are used to perform bit-level operations on the operands.
Bitwise Operators

• The operators are first converted to bit-level and then the calculation is performed on the
operands.
• Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing.

Assignment Operators

• These operators are used to assign value to a variable.


• The left side operand of the assignment operator is a variable and the right side operand
of the assignment operator is a value.
• The value on the right side must be of the same data type as the variable on the left side
otherwise the compiler will raise an error.
Examples #include <iostream>
#include <iostream> using namespace std;
using namespace std;
int main()
int main()
{ {
int a = 6, b = 4; int a = 6, b = 4;
// Binary AND operator
cout << "a & b is " << (a & b) << endl; // Assignment Operator
cout << "a = " << a << endl;
// Binary OR operator
cout << "a | b is " << (a | b) << endl;
// Add and Assignment Operator
// Binary XOR operator cout << "a += b is " << (a += b) << endl;
cout << "a ^ b is " << (a ^ b) << endl;

// Left Shift operator // Subtract and Assignment Operator


cout << "a<<1 is " << (a << 1) << endl; cout << "a -= b is " << (a -= b) << endl;
// Right Shift operator
cout << "a>>1 is " << (a >> 1) << endl; // Multiply and Assignment Operator
cout << "a *= b is " << (a *= b) << endl; Output
// One’s Complement operator Output: a=6
cout << "~(a) is " << ~(a) << endl;
a & b is 4 // Divide and Assignment Operator a += b is 10
return 0; a | b is 6 cout << "a /= b is " << (a /= b) << endl;
a -= b is 6
}
a ^ b is 2 a *= b is 24
a<<1 is 12 return 0;
} a /= b is 6
a>>1 is 3
~(a) is -7
Ternary or Conditional Operators(?:)

• This operator returns the value based on the #include <iostream>


condition. using namespace std;

• Expression1? Expression2: Expression3 int main()


{
• The ternary operator ? determines the answer int a = 3, b = 4;
based on the evaluation of Expression1.
// Conditional Operator
• If it is true, then Expression2 gets evaluated int result = (a < b) ? b : a;
and is used as the answer for the expression. cout << "The greatest number is "
<< result << endl;
• If Expression1 is false, then Expression3 gets
evaluated and is used as the answer for the return 0;
expression. }

• This operator takes three operands, therefore


Output:
it is known as a Ternary Operator. The greatest number is 4
Type Conversions
• Type conversion is the process that converts the predefined data type of one variable
into an appropriate data type.
• The main idea behind type conversion is to convert two different data type variables
into a single data type to solve mathematical and logical expressions easily without
any data loss.
• For example, we are adding two numbers, where one variable is of int type and
another of float type; we need to convert or typecast the int variable into a float to
make them both float data types to add them.

 Type conversion can be done in two ways in C++, one is implicit type conversion,
and the second is explicit type conversion.
 Those conversions are done by the compiler itself, called the implicit type or
automatic type conversion.
 The conversion, which is done by the user or requires user interferences called the
explicit or user-defined type conversion.
Implicit Type Conversion

• The implicit type conversion is the type of conversion done automatically by the
compiler without any human effort.
• It means an implicit conversion automatically converts one data type into another
type based on some predefined rules of the C++ compiler.
• Hence, it is also known as the automatic type conversion.
For example:
int x = 20;
short int y = 5;
int z = x + y;
• The C++ compiler automatically converts the lower rank data type (short int)
value into a higher type (int) before resulting in the sum of two numbers.
• Thus, it avoids the data loss, overflow, or sign loss in implicit type conversion of
C++.
Order of the typecast in implicit conversion
• The following is the correct order of data types from lower rank to higher rank:
bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int -> long long int -
> float -> double -> long double
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // assign the integer value
6. int num1 = 25;
7. // declare a float variable
8. float num2;
9. // convert int value into float variable using implicit conversion
10.num2 = num1;
11.cout << " The value of num1 is: " << num1 << endl;
12.cout << " The value of num2 is: " << num2 << endl; The value of num1 is: 25
The value of num2 is: 25
13.return 0;
14.}
Explicit type conversion

• Conversions that require user intervention to change the data type of


one variable to another, is called the explicit type conversion.
• Hence, it is also known as typecasting.
• Generally, we force the explicit type conversion to convert data from one
type to another because it does not follow the implicit conversion rule.
• The explicit type conversion is divided into two ways:
1.Explicit conversion using the cast operator
2.Explicit conversion using the assignment operator
• Cast operator: In C++ language, a cast operator is a unary operator who
forcefully converts one type into another type.
Example
#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;
}
• Output: The value of x is: 6
Types of Casting
C++ supports four types Const_cast conversion Adds or removes const
of casting:
Static_cast conversion Performs basic conversions
• Static Cast Performs checked
• Dynamic Cast Dynamic_cast conversion
polymorphic conversions
• Const Cast
• Reinterpret Cast Reinterpret_cast conversion
Performs general low-level
conversions

Implicit conversions from


Standard conversions
one type to another
Conditional and Looping Statements

1. if, else, else-if, switch --------------- Conditional


2. for, while, and do-while ---------------- Looping
Conditional Statements int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
int main () { if (num <0 || num >100)
int main () { {
int num = 11;
int num = 10; cout<<"wrong number";
if (num % 2 == 0) }
if (num % 2 == 0) { else if(num >= 0 && num < 50){
cout<<"It is even cout<<"Fail";
{
number"; }
cout<<"It is even number"; } else if (num >= 50 && num < 60)
else {
{ cout<<"D Grade";
}
}
cout<<"It is odd
return 0; else if (num >= 60 && num < 70)
number"; {
} } cout<<"C Grade";
return 0; }
} else if (num >= 70 && num < 80)
{
cout<<"B Grade";
} ……………….
}
Conditional Statements - Switch

int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num)
{
case 10: cout<<"It is 10"; break;
case 20: cout<<"It is 20"; break;
case 30: cout<<"It is 30"; break;
default: cout<<"Not 10, 20 or 30"; break;
}
}
Looping Statements – For ,While
for(initialization; condition; incr/decr) while(condition)
{ {
//code to be executed //code to be executed
}
}
Eg,
Eg, int main() {
int main() { int i=1;
while(i<=10)
for(int i=1;i<=10;i++){ {
cout<<i <<"\n"; cout<<i <<"\n";
} i++;
} }
}
Looping Statements – do While
do{
//code to be executed
}while(condition);
Eg, int main() {
int i = 1;
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
}
Others Looping Statements
• Break
• Continue
• Goto
• Comments
Arrays
• Array in C++ is a group of similar types of elements that have contiguous
memory locations.
• In C++ std::array is a container that encapsulates fixed-size arrays. In C++,
the array index starts from 0. We can store only a fixed set of elements in a C+
+ array.
• A collection of related data items stored in adjacent memory places is referred
to as an array in the C/C++ programming language or any other programming
language for that matter.
• Elements of an array can be accessed arbitrarily using its indices. They can be
used to store a collection of any type of primitive data type, including int,
float, double, char, etc.
• An array in C/C++ can also store derived data types like structures, pointers,
and other data types, which is an addition.
The array representation in a picture Advantages of C++ Array

•Code Optimization (less code)


•Random Access
•Easy to traverse data
•Easy to manipulate data
•Easy to sort data etc.
Why do we need arrays?
Disadvantages of C++ Array
With a limited number of objects, we can use regular variables (v1, v2,
v3,..), but when we need to hold many instances, managing them with •Fixed size
normal variables becomes challenging. To represent numerous instances
in one variable, we use an array.

Important things to remember while using arrays in C++

1.The array's indexes begin at 0. Meaning that the first item saved at index 0 is x[0].
2.The final element of an array with size n is kept at index (n-1). This example's final element is x[5].
3.An array's elements have sequential addresses. Consider the scenario where x[0beginning ]'s
address is 2120.
C++ Array Types
There are 2 types of arrays in C++ programming:
• Single Dimensional Array : Each element in this kind of array is described by one indexes
• Multidimensional Array : Each element in this kind of array is described by two indexes, the first of which
denotes a row and the second of which denotes a column.

Example:
#include <iostream>
using namespace std;
Output:
int main()
{ 10
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array 0
//traversing array 20
0
for (int i = 0; i < 5; i++)
30
{
cout<<arr[i]<<"\n";
}
}
How to display the sum and average of array elements?

#include <iostream>
using namespace std;
int main() {
// initialize an array without specifying the size
double numbers[] = {7, 5, 6, 12, 35, 27};
double sum = 0;
double count = 0;
double average;
cout << "The numbers are: ";
// print array elements
// use of range-based for loop
for (const double &n : numbers) {
cout << n << " ";
// calculate the sum
sum += n;
// count the no. of array elements
++count;
}
// print the sum
cout << "\nTheir Sum = " << sum << endl;
// find the average
average = sum / count;
cout << "Their Average = " << average << endl;

return 0;
}

Output:
The numbers are: 7 5 6 12 35 27 Their Sum = 92 Their Average = 15.3333
Classes and Objects
• Everything in C++ is associated with classes and objects, along with
its attributes and methods. For example: in real life, a car is an object.
• The car has attributes, such as weight and color, and methods, such
as drive and brake.
• Attributes and methods are basically variables and functions that
belongs to the class. These are often referred to as "class members".
• A class is a user-defined data type that we can use in our program, and
it works as an object constructor, or a "blueprint" for creating objects.
• To create a class, use the class keyword.
Access Specifiers
• Control the visibility and accessibility of class members. There are
three access specifiers in C++.
• Public: Members declared as public are accessible from any part of
the program. They have no restrictions on access.
• Private: Members declared as private are only accessible within the
class. They cannot be accessed directly from outside the class.
• Protected: Members declared protected are similar to private
members but can also be accessed by derived classes.
Example

Create a class called "MyClass":

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Create an Object

class MyClass { // The class


• In C++, an object is created from
public: // Access specifier
a class. int myNum; // Attribute (int variable)
• We have already created the class string myString; // Attribute (string variable)
};
named MyClass, so now we can
use this to create objects. int main() {
• To create an object of MyClass, MyClass myObj; // Create an object of MyClass
specify the class name, followed // Access attributes and set values
by the object name. myObj.myNum = 15;
• To access the class attributes myObj.myString = "Some text";
(myNum and myString), use the // Print attribute values
dot syntax (.) on the object. cout << myObj.myNum << "\n";
• Create an object called "myObj" cout << myObj.myString;
return 0;
and access the attributes: }

Output: 15
Some text
C++ Class Methods

Methods are functions that belongs to the class.


There are two ways to define functions that belongs to a class:
•Inside class definition
•Outside class definition
In the following example, we define a function inside the class, and we name it "myMethod".
We access methods just like you access attributes; by creating an object of the class and using the dot syntax (.).

Example for Inside class definition:

class MyClass { // The class


public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Example for Outside class definition

• To define a function outside the class definition, you have to declare it inside the class and then
define it outside of the class. This is done by specifying the name of the class, followed by the
scope resolution:: operator, followed by the name of the function.
Example:
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};

// Method/function definition outside the class


void MyClass::myMethod() {
cout << "Hello World!";
}

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Abstraction
• Data Abstraction is a process of providing only the essential details to the outside world and hiding the
internal details, i.e., representing only the essential details in the program.
• Data Abstraction is a programming technique that depends on the seperation of the interface and
implementation details of the program.
• Let's take a real life example of AC, which can be turned ON or OFF, change the temperature, change
the mode, and other external components such as fan, swing. But, we don't know the internal details of
the AC, i.e., how it works internally. Thus, we can say that AC seperates the implementation details
from the external interface.
• C++ provides a great level of abstraction. For example, pow() function is used to calculate the power of
a number without knowing the algorithm the function follows.
• In C++ program if we implement class with private and public members then it is an example of data
abstraction.
Access Specifiers Implement Abstraction:
• Public specifier: When the members are declared as public, members can be accessed anywhere from
the program.
• Private specifier: When the members are declared as private, members can only be accessed only by
the member functions of the class.
Data Abstraction can be achieved in two ways:
•Abstraction using classes
•Abstraction in header files.

Abstraction using classes: An abstraction can be achieved using classes. A class is used to group all the
data members and member functions into a single unit by using the access specifiers. A class has the
responsibility to determine which data member is to be visible outside and which is not.

Abstraction in header files: Another type of abstraction is header file. For example, the pow() function
available is used to calculate the power of a number without actually knowing which algorithm function is
used to calculate the power. Thus, we can say that header files hide all the implementation details from the
user.
Let's see a simple example of abstraction in header files.

// program to calculate the power of a number.

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int n = 4;
int power = 3;
int result = pow(n,power); // pow(n,power) is the power function
std::cout << "Cube of n is : " <<result<< std::endl;
return 0;
}
Output:
Cube of n is : 64

In the above example, pow() function is used to calculate 4 raised to the power 3.
The pow() function is present in the math.h header file in which all the implementation details of
the pow() function is hidden.
Let's see a simple example of data abstraction using classes.

#include <iostream>
using namespace std;
class Sum
{
private: int x, y, z; // private variables
public:
void add()
{ Output:
cout<<"Enter two numbers: "; Enter two numbers: 3 6 Sum of two number is: 9

cin>>x>>y;
z= x+y; In this example, abstraction is
cout<<"Sum of two number is: "<<z<<endl; achieved using classes. A class
'Sum' contains the private members
} x, y and z are only accessible by
};
the member functions of the class.
int main()
{
Sum sm;
sm.add();
return 0;
}
Advantages Of Abstraction

• Implementation details of the class are protected from the inadvertent


user level errors.
• A programmer does not need to write the low-level code.
• Data Abstraction avoids the code duplication, i.e., programmer does
not have to undergo the same tasks every time to perform the similar
operation.
• The main aim of the data abstraction is to reuse the code and the
proper partitioning of the code across the classes.
• Internal implementation can be changed without affecting the user-
level code.
Encapsulation
• Encapsulation is an Object Oriented Programming concept that binds
together the data and functions that manipulate the data, and that
keeps both safe from outside interference and misuse.
• Data encapsulation led to the important OOP concept of data hiding.
• Data encapsulation is a mechanism of bundling the data, and the
functions that use them and data abstraction is a mechanism of
exposing only the interfaces and hiding the implementation details
from the user.
• C++ supports the properties of encapsulation and data hiding through
the creation of user-defined types, called classes.
• By default, all items defined in a class are private.
Example:
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

• The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your
program. This is one way encapsulation is achieved.
• To make parts of a class public (i.e., accessible to other parts of your program), you
must declare them after the public keyword. All variables or functions defined after
the public specifier are accessible by all other functions in your program.
• Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from
all other classes as possible.
Data Encapsulation Example

#include <iostream>
using namespace std;
class Adder {
public:
Output:
Adder(int i = 0) // constructor Total 60
{ total = i; }
Here, class adds numbers
void addNum(int number) // interface to outside world together, and returns the sum.
{ total += number; }
The public members addNum
int getTotal() // interface to outside world
{ return total; }; and getTotal are the interfaces
private: to the outside world and a user
int total; // hidden data from outside world needs to know them to use the
}; class. The private member
total is something that is
int main() { hidden from the outside world,
Adder a; but is needed for the class to
a.addNum(10);
operate properly.
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}
UML
• UML is not a programming language, it is rather a visual language.
• We use UML diagrams to portray the behaviour and structure of a system.
• UML helps software engineers, businessmen and system architects with modelling,
design and analysis.
• The Object Management Group (OMG) adopted Unified Modelling Language as a
standard in 1997.
• The International Organization for Standardization (ISO) published UML as an
approved standard in 2005.
Need:
• Complex applications need collaboration and planning from multiple teams, hence it
requires a clear and concise way to communicate amongst them.
• UML becomes essential to communicate the following aspects with non-programmers
• essential requirements, functionalities and processes of the system.
• A lot of time is saved down the line when teams can visualize processes, user
interactions and static structure of the system.
UML-Diagrams
The UML diagrams are categorized into structural diagrams, behavioral diagrams, and also interaction
overview diagrams.
The diagrams are hierarchically classified in the following figure.
Purpose of Class Diagrams
UML Class Diagram
• The main purpose of class diagrams is to build a static view
of an application.
• The class diagram depicts a static view of an
• It is the only diagram that is widely used for construction,
application.
and it can be mapped with object-oriented languages.
• It represents the types of objects residing in the
• It is one of the most popular UML diagrams.
system and the relationships between them.
• Following are the purpose of class diagrams given below:
• A class consists of its objects, and also it may
• It analyses and designs a static view of an application.
inherit from other classes.
• It describes the major responsibilities of a system.
• A class diagram is used to visualize, describe,
• It is a base for component and deployment diagrams.
document various aspects of the system, and also
• It incorporates forward and reverse engineering.
construct executable software code.
• It shows the attributes, classes, functions, and
Benefits of Class Diagrams
relationships to give an overview of the software
system.
• It can represent the object model for complex systems.
• It constitutes class names, attributes, and functions
• It reduces the maintenance time by providing an overview of
in a separate compartment that helps in software
how an application is structured before coding.
development.
• It provides a general schematic of an application for better
• Since it is a collection of classes, interfaces,
understanding.
associations, collaborations, and constraints, it is
• It represents a detailed chart by highlighting the desired code,
termed as a structural diagram.
which is to be programmed.
• It is helpful for the stakeholders and the developers.
Vital Components of a Class Diagram

•Upper Section: The upper section encompasses the name of the class. A class is a
representation of similar objects that share 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 centre 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: 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: The lower section contains 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.
Relationships

In UML, relationships are of three types:

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

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.

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: 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: 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.
Abstract Classes
• In the abstract class, no objects can be a direct entity of the abstract class.
• The abstract class can neither be declared nor be instantiated.
• It is used to find the functionalities across the classes. 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.
• Since it does not involve any implementation for a given function, it is best
to use the abstract class with multiple objects.
• 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 a Class Diagram?
The class diagram is used most widely to construct software applications. It not only
represents a static view of the system but also 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, it is suggested to give a meaningful
name to the class diagram.
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 number of
unwanted property 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 its final version.
A class diagram describing the sales order system
UML Use Case Diagram

• A use case diagram is used to represent the dynamic behavior of a system.


• It encapsulates the system's functionality by incorporating use cases, actors, and their relationships.
• It models the tasks, services, and functions required by a system/subsystem of an application.
• It depicts the high-level functionality of a system and also tells how the user handles a system.

Purpose of Use Case Diagrams

The main purpose of a use case diagram is to portray the dynamic aspect of a system. It accumulates the system's
requirement, which includes both internal as well as external influences. It invokes persons, use cases, and several things
that invoke the actors and elements accountable for the implementation of use case diagrams. It represents how an entity
from the external environment can interact with a part of the system.
Following are the purposes of a use case diagram given below:
1.It gathers the system's needs.
2.It depicts the external view of the system.
3.It recognizes the internal as well as external factors that influence the system.
4.It represents the interaction between the actors.
How to draw a Use Case diagram?

• It is essential to analyze the whole system before starting with drawing a use case diagram, and then the
system's functionalities are found.
• Once every single functionality is identified, they are then transformed into the use cases to be used in
the use case diagram.
• After that, we will enlist the actors that will interact with the system.
• The actors are the person or a thing that invokes the functionality of a system.
• It may be a system or a private entity, such that it requires an entity to be pertinent to the functionalities
of the system to which it is going to interact.
• Once both the actors and use cases are enlisted, the relation between the actor and use case/ system is
inspected. It identifies the no of times an actor communicates with the system.
• An actor can interact multiple times with a use case or system at a particular instance of time.

Following are some rules that must be followed while drawing a use case diagram:

• A pertinent and meaningful name should be assigned to the actor or a use case of a system.
• The communication of an actor with a use case must be defined understandably.
• Specified notations to be used as and when required.
• The most significant interactions should be represented among the multiple noes of interactions between
the use case and actors.
Example of a Use Case Diagram

A use case diagram depicting the Online Shopping website is given below.
Here the Web Customer actor makes use of any online shopping website to purchase online. The top-level uses are as
follows; View Items, Make Purchase, Checkout, Client Register. The View Items use case is utilized by the customer
who searches and view products. The Client Register use case allows the customer to register itself with the website
for availing gift vouchers, coupons, or getting a private sale invitation. It is to be noted that the Checkout is an included
use case, which is part of Making Purchase, and it is not available by itself.
The View Items is further extended by several use cases such as; Search Items, Browse Items, View
Recommended Items, Add to Shopping Cart, Add to Wish list. All of these extended use cases provide some
functions to customers, which allows them to search for an item. The View Items is further extended by several
use cases such as; Search Items, Browse Items, View Recommended Items, Add to Shopping Cart, Add to Wish
list. All of these extended use cases provide some functions to customers, which allows them to search for an
item.
Both View Recommended Item and Add to Wish List include the Customer Authentication use case, as they
necessitate authenticated customers, and simultaneously item can be added to the shopping cart without any
user authentication.
Similarly, the Checkout use case also includes the following use cases, as shown below. It requires an
authenticated Web Customer, which can be done by login page, user authentication cookie ("Remember me"), or
Single Sign-On (SSO). SSO needs an external identity provider's participation, while Web site authentication
service is utilized in all these use cases.
The Checkout use case involves Payment use case that can be done either by the credit card and external credit
payment services or with PayPal.
Important tips for drawing a Use Case diagram

Following are some important tips that are to be kept in mind while drawing a use case
diagram:
1.A simple and complete use case diagram should be articulated.
2.A use case diagram should represent the most significant interaction among the
multiple interactions.
3.At least one module of a system should be represented by the use case diagram.
4.If the use case diagram is large and more complex, then it should be drawn more
generalized.

You might also like