Unit 1 CPP
Unit 1 CPP
Adding new data and functions is not easy. Adding new data and function is easy.
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.
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.
• 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
Or
• marks=cin.get();//A character is read and assigned to marks
• string name;
• cin>>name;
• string empname;
• cin.getline(empname,20);
• 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.
Local Variables
Global Variables
Formal Variables
Member Variables
Instance Variables
Examples
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 .
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
int main()
{
int a = 8, b = 3;
// 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.
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;
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
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
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
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
Output: 15
Some text
C++ Class Methods
• 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
};
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.
#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
• 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);
•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
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
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.