CSC 202 C++
CSC 202 C++
CSC 202
Computer Programming (CP) II
Complete lecture note
Prepared
By
1
Principles of good programming
Overview
Programming principles have helped many developers over the years and they becoming a better
programmer, and I believe, this programming principles will help a developers to become more
efficient and able to produce code which is easier to maintain. By following these coding
principles, you can save development and maintenance time.
What are the Programming principles?
• Programming is the process of coding, testing, troubleshooting, debugging and
maintaining a system.
• Programming principles help us to write excellent quality of code and maintain a good
coding practice
Why should a developer follow the principles?
• Actually, writing programs is often a matter of personal taste but there are certain
principles or guidelines that should be followed within your own style in order to make
programs easy to maintain and understand by both, you and others, and also principles
guide the creation of stable, scalable, and robust code.
What are the benefits if developer followed it?
• Readability:
All developers were in a team able to understand the code.
• Extensibility
In the software world, we should not blame the change requests; it’ll come at any time.
So our code is always easy to extend without breaking existing business rules.
• Maintainability
It’s easy to maintain by the development team and the production support team too
because the application is loosely coupled.
• Modularity
Divide a program into reusable pieces: functions, modules, libraries
2
Types of Programming Principles
DRY (Don’t-Repeat-Yourself)
Duplication can lead to maintenance nightmares, poor factoring, and logical contradictions.
"Every piece of knowledge must have a single, unambiguous, authoritative representation within
a system". In other words, a piece of logic should only be represented once in an application.
• Duplication is the root of all software evils.
• Duplication is a waste
KISS (Keep It Simple, Stupid)
• Nowadays programming languages, frameworks, and APIs have powerful means to
create sophisticated solutions for various kinds of problems. Sometimes developers might
feel tempted to write “clever” solutions that use all these complex features.
• The KISS principle states that most systems work best if they are kept simple rather than
making them complex; therefore simplicity should be a key goal in design and
unnecessary complexity should be avoided.
• This principle can be applied to any scenario, including many business activities, such as
planning, designing, and development.
YAGNI (You Aren’t Going to Need It)
• As developers, we'll always think a lot about the future usability of the project and try to
do some extra features coding in a mind that “just in case we need them” or “we will
eventually need them”.
• Just one word… Wrong! I’ll repeat it this way: You didn’t need it, you don’t need it, and
in most of the cases… “You Aren’t Going to Need It”.
• YAGNI states that "don’t implement something until it is necessary".
• There are two main reasons to practice YAGNI,
• You save time because you avoid writing code that you turn out not to need.
• Your code is better because you avoid polluting it with 'guesses' that turn out to be
more or less wrong but stick around anyway.
SOLID
• SOLID principles are the design principles that enable us to manage with most of the
software design problems.
• Robert C. Martin compiled these principles in the 1990s.
3
• These principles provide us ways to move from tightly coupled code and little
encapsulation to the desired results of loosely coupled and encapsulated real needs of a
business properly.
• SOLID principle supports good object-oriented design and programming. Five of these
principles are described as SOLID:
• S: Single responsibility,
• O: Open-closed,
• L: Liskov substitution,
• I: Interface segregation, and
• D: Dependency inversion.
Single Responsibility
• A component of code (e.g. class or function) should perform a single well defined task.
• SRP says "Every software module should have only one reason to change".
• This means that every class, or similar structure, in your code should have only one job to
do. Everything in that class should be related to a single purpose.
Open/Closed Principle
• Software entities (classes, modules, functions, etc.) should be open for extension, but
closed for modification. In other words, don't write classes that people can modify, write
classes that people can extend.
• "Open for extension" means, we need to design our module/class in such a way that the
new functionality can be added only when new requirements are generated.
• "Closed for modification" means we have already developed a class and it has gone
through unit testing.
Liskov Substitution Principle
• The Liskov Substitution Principle (LSP) states that "you should be able to use any
derived class instead of a parent class and have it behave in the same manner without
modification".
• It ensures that a derived class does not affect the behavior of the parent class, in other
words that a derived class must be substitutable for its base class.
• This principle is just an extension of the Open Close Principle and it means that we must
ensure that new derived classes extend the base classes without changing their behavior.
4
Interface Segregation Principle (ISP)
• The Interface Segregation Principle states "that clients should not be forced to implement
interfaces they don't use.
• Instead of one fat interface many small interfaces are preferred based on groups of
methods, each one serving one sub module."
• Means an interface should be more closely related to the code that uses it than code that
implement it.
• So the methods on the interface are defined by which methods the client code needs
rather than which methods the class implements. So clients should not be forced to
depend upon interfaces that they don't use.
Dependency Inversion Principle
• The Dependency Inversion Principle (DIP) states that high-level modules/classes should
not depend on low-level modules/classes.
• Both should depend upon abstractions.
• Secondly, abstractions should not depend upon details.
• Details should depend upon abstractions.
High-level modules/classes implement business rules or logic in a system (application). Low-
level modules/classes deal with more detailed operations; in other words they may deal with
writing information to databases or passing messages to the operating system or services.
5
Structure of C++ Program
It is a common practice to organize a program into three separate files. The class declarations are
placed in a header file and the definitions of member functions go into another file. This
approach enables the programmer to separate the abstract specification of the interface from the
implementation details (member function definition).
Finally, the main program that uses the class is places in a third file which “includes: the
previous two files as well as any other file required.
The class definition including the member functions constitute the server that provides services
to the main program known as client. The client uses the server through the public interface of
the class.
6
First C++ Program- Hello Fugus!
In this part we will write and understand the first program in C++ programming. We are
writing a simple C++ program that prints “Hello Fugus!” message. Let’s see the program first
and then we will discuss each and every part of it in detail.
Example 1:
Output
Output:
7
Explanatory of the above program C++
#include<iostream>
• The #include is directive instructs the compiler to include the contents of the file enclosed
within angular brackets into the source file.
• The header file iostream should be included at the beginning of all programs that use
input/output statements e.g.
• #include<conio> or #include<conio.h>
• #include<math> or #include<math.h> //for pow()function
• #include<string> or #include<string.h> //for strcpy() etc.
using namespace std;
• Namespace is a new concept introduced by the ANSI C++ standards committee.
• This defines a scope for the identifiers that are used in a program. For using the identifier
defined in the namespace scope we must include the using directive
• Here, std is the namespace where ANSI C++ standard class libraries are defined. All
ANSI C++ programs must include this directive.
• This will bring all the identifiers defined in std to the current global scope. Using and
namespace are the new keyword of C++.
Comments:
• Comments as the names suggests are just a text written by programmer during code
development.
• Comment doesn’t affect your program logic in any way, you can write whatever you
want in comments but it should be related to the code and have some meaning so that
when someone else look into your code, the person should understand what you did in the
code by just reading your comment.
• This improves readability of your code and when you are working on a project with your
team mates, this becomes essential aspect.
There are two types of comments in the above program.
• Single line comment e.g.
/* This function adds two integer numbers
* and returns the result as an integer value
*/
• Multiple line comment e.g.
// Read Numbers or // from keyboard etc.
8
int main()
• As the name suggests, this is the main function of our program and the execution of
program begins with this function, the int here is the return type which indicates to the
compiler that this function will return a integer value.
• Therefore, every main () in C++ should end with a return (0) statement; otherwise a
warning an error might occur.
cout << “Hello Fugus!”;
• The cout object belongs to the iostream file and the purpose of this object is to display
the content between double quotes as it is on the screen.
• This object can also display the value of variables on screen
• A semicolon to terminate end of the statement.
return 0;
• This statement returns value 0 from the main() function which indicates that the
execution of main function is successful.
Variables in C++
• A variable is a name which is associated with a value that can be changed. For example
when I write int num=20; here variable name is num which is associated with value 20,
int is a data type that represents that this variable can hold integer values.
Syntax of declaring a variable in C++
• data_type variable1_name = value1, variable2_name = value2; e.g.
• num1=20;
num2=100;
Types of variables
• Variables can be categorized based on their data type. For example, in the above example
we have seen integer types variables.Following are the types of variables available in
C++.
• int: These type of variables holds integer value.
• char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.
9
• bool: holds boolean value true or false.
• double: double-precision floating point value.
• float: Single-precision floating point value
Types of variables based on their scope
In our first program we have seen the curly braces in the program like this:
• Any variable declared inside these curly braces have scope limited within these curly
braces, if you declare a variable in main() function and try to use that variable outside
main() function then you will get compilation error.
In C++ there are four kinds of scope as given below:
• Global variables (File scope ).
• Local variables (Local scope).
• Function scope
• Class scope
Global variable (file scope)
• A variable declared outside of any function (including main as well) is called global
variable.
• Global variables have their scope throughout the program, they can be accessed
anywhere in the program, in the main, in the user defined function, anywhere
• If the declaration of an identifier appears outside all functions, it is available to all the
functions in the program and its scope becomes file scope.
• Example 1:
Example 2:
Local variable
• Local variables are declared inside the braces of any user defined function, main
function, loops or any control statements (if, if-else etc) and have their scope limited
inside those braces.
• A block in C++ is enclosed by a pair of curly braces i.e., ‘{‘ and ‘}’.
• The variables declared within the body of the block are called local variables and can be
used only within the block.
• Example 1:
11
Example 2:
12
Flow Chart of Data types in C++
13
Basic Arithmetic Operators
• Basic arithmetic operators are: +, -, *, /, %
• + is for addition.
• – is for subtraction.
• * is for multiplication.
• / is for division.
• % is for modulo.
Note: Modulo operator returns remainder, for example 20 % 5 would return 0
Example
Assignment Operators
• Assignments operators in C++ are: =, +=, -=, *=, /=, %= e.g.
• num2 = num1 would assign value of variable num1 to the variable.
• num2+=num1 is equal to num2 = num2+num1
• num2-=num1 is equal to num2 = num2-num1
• num2*=num1 is equal to num2 = num2*num1
• num2/=num1 is equal to num2 = num2/num1
• num2%=num1 is equal to num2 = num2%num1
Example
14
Auto-increment and Auto-decrement Operators
• ++ and —
num++ is equivalent to num=num+1;
• num–- is equivalent to num=num-1;
Logical Operators
• Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.
• Logical operators in C++ are: &&, ||, !
• Let’s say we have two boolean variables b1 and b2.
• b1&&b2 will return true if both b1 and b2 are true else it would return false.
• b1||b2 will return false if both b1 and b2 are false else it would return true.
• !b1 would return the opposite of b1, that means it would be true if b1 is false and it would
return false if b1 is true.
Example
Relational operators
• We have six relational operators in C++: ==, !=, >, <, >=, <=
• == returns true if both the left side and right side are equal
• != returns true if left side is not equal to the right side of operator.
• > returns true if left side is greater than right.
• < returns true if left side is less than right side.
• >= returns true if left side is greater than or equal to right side.
• <= returns true if left side is less than or equal to right side.
15
Example
16
Statements
Statement perform a number of tasks, such as computing, storing the results of computations,
altering the flow of control, reading and writing from or onto devices (or files), and providing the
information for the compiler.
A computer program is a set instruction for a computer. These instructions, also known as
statements, are executed sequentially that is one after the other as they appear in a program.
1. Executable
2. Non-executable.
Executable statements: are those statements that result in a machine code i.e., causes an action to
be performed.
Examples:
a) if statement
b) nested if statement
c) if-else statement
d) nested if-else statement
e) if else if statement
f) Switch statement
a) if statement in C++
true
Exp
Statement
false
17
The expression may represent a relation expression, a logical expression, a numeric variable or a
numeric constant. The specified expression may be a simple expression or compound expression.
The expression in C++ language evaluates to a zero or non-zero value. If expression evaluates to
a non-zero value, then the statement in the statement block are executed; otherwise they are
bypassed.
Example of if statement:
Output
If statement can be nested, i.e., an if statement can be contained within another if statement. The
inner if statement will be executed if the expression of the outer of statement evaluates to non-
zero value.
if (expression_1){
Statement(s);
if (expression_2){
Statement(s);
}
}
18
Statement1 would execute if the expression_1 is true. Statement2 would only execute if both the
conditions (expression_1 and expression_2) are true.
Output
More examples:
Output
19
c) if –else Statement in C++
Sometimes you have a condition and you want to execute a block of code if condition is true and
execute another piece of code if the same condition is false. This can be achieved in C++ using
if-else statement.
if (expression)
{
Statement(s)_1
}
else
{
Statement(s)_2
}
Exp
false true
Statement Statement
If expression evaluates is true, the statement_1 is executed and the statement_2 is bypassed.
However, if the expression evaluates is false, the statement_1 is bypassed and the statement_2 is
executed.
20
Output
Output
21
e) if –else if statement in C++
if-else-if statement is used when we need to check multiple conditions. In this control structure
we have only one “if” and one “else”, however we can have multiple “else if” blocks. This is
how it looks:
if (expression_1){
// if expression is true execute this
Statement(s);
}
else if (expression_2) {
// execute this if expression_1 is not met and expression_2 is met
Statement(s);
}
else if (expression_3){
// execute this if exp_1 and exp_2 are not met and exp_3 is met
Statement(s);
}
.
.
else {
// if none of the expression is true
// then those statements gets executed
Statement(s);
}
Note: The most important point to note here is that in if-else-if, as soon as the condition is met,
the corresponding set of statements get executed, rest gets ignored. If none of the condition is
met then the statements inside “else” gets executed.
Example of if-else-if
22
Output
If expression takes any value from val-2, val-2, val-3,…..val-n, the control is transferred to that
appropriate case. In each case, the statement are executed and then the break statement transfers
the control out of switch statement. If no break statement is used following a case, except last the
one in the absence of default keyword, the control will fall through to the next case. If the value
23
of the expression does no match any of the case values, control goes to the default keyword,
which is usually at the end of the switch statement. The use of the default keyword can be of a
great convenience. If there is no default keyword, the whole switch statement simple terminates
when there is no match.
= val-1 default
Exp
= val-2 = val-3 = val-n
Output
24
Examples:
a) for statement
b) while statement
c) do – while statement
Init
false
Test
true
Statement
Increment/discre
ment
Where init is an expression to initialize the counter, the test is an expression to see when to stop
iterating, and increment/decrement is an expression to increment/decrement the counter for each
pass of the loop. The init and increment/decrement parts can have more than one statement
separated by a comma.
The increment/decrement for the counter can be positive as well as negative and illustration
show below:
a) for (i = 1; i<= n; i++){
// Statement
}
25
Set i=1
false
I<=n
true
Statement
I++
Set i=n
false
I>=n
true
Statement
I--
26
Output
Output
27
Infinite for loop in C++
A loop is said to be infinite when it executes repeatedly and never stops. This usually happens by
mistake. When you set the condition in for loop in such a way that it never return false, it
becomes infinite loop.
Output
This is an infinite loop as we are incrementing the value of i so it would always satisfy the
condition i>=1, the condition would never return false.
In while loop, condition is evaluated first and if it returns true then the statements inside while
loop execute, this happens repeatedly until the condition returns false. When condition returns
false, the control comes out of loop and jumps to the next statement in the program after while
loop.
while (condition)
{
Statement(s);
}
28
While Loop example in C++
Test Runs
29
An example of infinite while loop:
This loop would never end as I’m decrementing the value of i which is 1 so the condition i<=6
would never return false.
Output
do-while loop is similar to while loop, however there is a difference between them: In while
loop, condition is evaluated first and then the statements inside loop body gets executed, on the
other hand in do-while loop, statements inside do-while gets executed first and then the condition
is evaluated.
do
{
Statement(s);
}while(condition);
First, the statements inside loop execute and then the condition gets evaluated, if the condition
returns true then the control jumps to the “do” for further repeated execution of it, this happens
repeatedly until the condition returns false. Once condition returns false control jumps to the next
statement in the program after do-while.
30
Using code of do while Statement
31
3. Jumping: This statement transferring control from one point to another point in the same
program unit.
Example:
a) break statement
b) continue statement
c) goto statement
a) Break statement in C++
The break statement is used in following two scenarios:
a) Use break statement to come out of the loop instantly. Whenever a break statement is
encountered inside a loop, the control directly comes out of loop terminating it. It is used along
with if statement, whenever used inside loop(see the example below) so that it occurs only for a
particular condition.
b) It is used in switch case control structure after the case blocks. Generally all cases in switch
case are followed by a break statement to avoid the subsequent cases (see the example below)
execution. Whenever it is encountered in switch-case block, the control comes out of the switch-
case body.
break;
Output
33
Example: break statement in switch loop
Output
In this example, we have break statement after each Case block, this is because if we don’t have
it then the subsequent case block would also execute. The output of the same program without
break would be:
continue;
34
Example: continue statement inside for loop
As you can see that the output is missing the value 3, however the for loop iterate though the
num value 0 to 6. This is because we have set a condition inside loop in such a way, that the
continue statement is encountered when the num value is equal to 3. So for this iteration the loop
skipped the cout statement and started the next iteration of loop.
Test Runs
35
Output
Output
36
goto statement in C++
The goto statement is used for transferring the control of a program to a given label. The syntax
of goto statement looks like this:
goto label_name;
Program structure:
label1:
...
...
goto label2;
...
..
label2:
...
In a program we have any number of goto and label statements, the goto statement is followed by
a label name, whenever goto statement is encountered, the control of the program jumps to the
label specified in the goto statement.
goto statements are almost never used in any development as they are complex and makes your
program much less readable and more error prone. In place of goto, you can
use continue and break statement.
Output
Functions in C++
A function is block of code which is used to perform a particular task, for example let’s say you
are writing a large program with C++ and in that program you want to do a particular task
several number of times, like displaying value from 1 to 10, in order to do that you have to write
few lines of code and you need to repeat these lines every time you display values. Another way
37
of doing this is that you write these lines inside a function and call that function every time you
want to display values.
Output
38
Function declaration in C++
The syntax of function declaration is
Using code
The function declaration consists only of a function header; contains no code. Function header
consists of three parts, those are the return type, the function name, and the formal argument list.
A semicolon follows the function header.
Example:
1. int sum(int num1, int num2); or
2. int sum(int, int);
You are telling the compiler that the return type of the function is int, name of the function is
sum and it has two argument all of type int.
39
We can call the function like this:
Example:
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
Types of functions
1) Build-it functions
Built-in functions are also known as library functions. We need not to declare and define these
functions as they are already written in the C++ libraries such as iostream, cmath etc. We can
directly call them when we need.
Example
Here we are using built-in function pow(x,y) which is x to the power y. This function is declared
in cmath header file so we have included the file in our program using #include directive.
Output
40
2) User-defined functions
We have already seen user-defined functions, the example we have given at the beginning of this
class is an example of user-defined function. The functions that we declare and write in our
programs are user-defined functions. Let have more example of user-defined functions .
Output
41
Output
42
Output
Recursion
The process in which a function calls itself is known as recursion and the corresponding function
is called the recursive function. The popular example to understand the recursion is factorial
function.
Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. In the following
diagram. I have shown that how the factorial function is calling itself until the function reaches
to the base condition.
43
C++ recursion example: Factorial
Output
Indirect recursion: When function calls another function and that function calls the calling
function, then this is called indirect recursion. For example: function A calls function B and
Function B calls function A.
Output:
44
Arrays in C++
int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Method 2:
Method 3:
45
Output
Noted although this code worked fine, displaying all the elements of array like this is not
recommended, when you want to access a particular array element then this is fine but if you
want to display all the elements then you should use a loop.
You can pass array as an argument to a function just like you pass variables as arguments. In
order to pass array to the function you just need to mention the array name during function
call like this:
function_name(array_name);
46
Example
we are passing two arrays a & b to the function sum(). This function adds the
corresponding elements of both the arrays and display them.
Output
Strings
Strings are words that are made up of characters, hence they are known as sequence of
characters. In C++ we have two ways to create and use strings: 1) By creating char arrays and
treat them as string 2) By creating string object.
Output:
47
Example 2: Getting user input as string
This can be considered as inefficient method of reading user input, why? Because when we read
the user input string using cin then only the first word of the string is stored in char array and
rest get ignored. The cin function considers the space in the string as delimiter and ignore the
part after it.
Output
1) Size of the char array is fixed, which means the size of the string created through it is fixed in
size, more memory cannot be allocated to it during runtime. For example, lets say you have
created an array of character with the size 10 and user enters the string of size 15 then the last
five characters would be truncated from the string. On the other hand if you create a larger array
to accommodate user input then the memory is wasted if the user input is small and array is
much larger then what is needed.
2) In this method, you can only use the in-built functions created for array which don’t help
much in string manipulation.
48
String object in C++
Now we have seen how to handle strings in C++ using char arrays. Lets see another and better
way of handling strings in C++ – string objects.
Output
The advantage of using this method is that you need not to declare the size of the string, the size
is determined at run time, so this is better memory management method. The memory is
allocated dynamically at runtime so no memory is wasted.
Debugging: Debugging is a process of fixing the bugs found in testing phase and
Programmer or developer is responsible for debugging and it can’t be automated
Testing: Testing is a process of finding bugs or errors in a software product that is done
manually by tester or can be automated
Testing Debugging
The purpose of testing is to find bugs and The purpose of debugging is to correct
errors. those bugs found during testing.
49
It can be automated. It can’t be automated.
Most of the testing can be done without Debugging can’t be done without proper
design knowledge. design knowledge.
50
Oops Concept in C++
The main purpose of C++ programming was to add object orientation to the C programming
language, which is in itself one of the most powerful programming languages. If any
programming language follow below oops concept then that language called object oriented
programming language.
• Object
• Class
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
Object
Object is the physical as well as logical entity whereas class is the only logical entity.
Class
Class: Class is a blue print which is containing only list of variables and method and no memory is
allocated for them. A class is a group of objects that has common properties.
Encapsulation
Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation.
Encapsulation is achieved in C++ language by class concept. The main advantage of using of encapsulation
is to secure the data from other methods, when we make a data private then these data only use within the
class, but these data not accessible outside the class.
Abstraction
Abstraction is the concept of exposing only the required essential characteristics and behavior with respect
to a context.
Hiding of data is known as data abstraction. In object oriented programming language this is
implemented automatically while writing the code in the form of class and object.
Inheritance
The process of obtaining the data members and methods from one class to another class is known
as inheritance. It is one of the fundamental features of object-oriented programming.
Polymorphism
The process of representing one Form in multiple forms is known as Polymorphism. Here one form
represent original form or original method always resides in base class and multiple forms represents
overridden method which resides in derived classes.
51
Access Specifiers in C++
Access specifiers in C++ define how the members of the class can be accessed. C++ has 3
new keywords introduced, namely.
• public
• private
• protected
The keywords public, private, and protected are called access specifiers. A class can have
multiple public, protected, or private labeled sections.
Note: By default, all members and function of a class is private i.e if no access specifier is
specified.
52
Syntax
Syntax
Output
53
Protected Access Specifier in C++
It is similar to private access specifier. It makes class member inaccessible outside the class.
But they can be accessed by any subclass of that class.
Syntax
54
Output
Example:
55
In real world many examples of object and class like dog, cat, and cow are belong to animal's
class. Each object has state and behaviors. For example a dog has state:- color, name, height,
age as well as behaviors:- barking, eating, and sleeping.
Animal class
Vehicle class
Car, bike, truck these all are belongs to vehicle class. These Objects have also different states
and behaviors. For Example car has state - color, name, model, speed, Mileage. As well as
behaviors - distance travel.
Difference between Class and Object in C++
Class Object
One class definition should exist only For one class multiple objects can be
3
once in the program. created.
56
Syntax to declare a Class
Syntax
Output
Inheritance in C++
The process of obtaining the data members and methods from one class to another class is
known as inheritance. It is one of the fundamental features of object-oriented programming.
Important points
• In the inheritance the class which is give data members and methods is known as base or
super or parent class.
• The class which is taking the data members and methods is known as sub or derived or
child class.
57
Syntax
The real life example of inheritance is child and parents, all the properties of father are
inherited by his son.
Diagram
In the above diagram data members and methods are represented in broken line are inherited
from faculty class and they are visible in student class logically.
Advantage of Inheritance
If we develop any application using this concept than that application has following
advantages,
• Application development time is less.
• Application takes less memory.
• Application execution time is less.
• Application performance is enhancing (improved).
• Redundancy (repetition) of the code is reduced or minimized so that we get consistence
results and less storage cost.
58
Types of Inheritance
Based on number of ways inheriting the feature of base class into derived class it has five types
they are:
• Single inheritance
• Multilevel inheritance
• Hierarchical inheritance
• Multiple inheritance
• Hybrid inheritance
Single inheritance
In single inheritance there exists single base class and single derived class.
Multilevel inheritances
In multilevel inheritances there exists single base class, single derived class and multilevel
intermediate base classes.
Single base class + single derived class + multilevel intermediate base classes
Intermediate base classes
An intermediate base class is one in one context with access derived class and in another
context same class access base class.
59
Multiple inheritance
In multiple inheritances there exist multiple classes and single derived class.
Hierarchical inheritance
Derivation of two or more classes from a single base class, Class A is only base class and classes
B and C are derived classes.
Hybrid inheritance
Combination of any inheritance type
60
Inheriting the feature from base class to derived class
In order to inherit the feature of base class into derived class we use the following
Syntax
Explanation
• classname-1 and classname-2 represents name of the base and derived classes respectively.
• : is operator which is used for inheriting the features of base class into derived class it
improves the functionality of derived class.
Example of Inheritance
Output
Abstraction in C++
Abstraction is the concept of exposing only the required essential characteristics and behavior
with respect to a context.
61
Hiding of data is known as data abstraction. In object oriented programming language this is
implemented automatically while writing the code in the form of class and object.
Real life example of Abstraction in C++
Abstraction shows only important things to the user and hides the internal details for example
when we ride a vehicle, we only know about how to ride vehicle but cannot know about how it
work and also we do not know internal functionality of vehicle.
Example of Abstraction
Output
Note: Data abstraction can be used to provide security for the data from the unauthorized
methods.
62
Note: Note: In C++ language data abstraction can be achieved by using class.
Encapsulation in C++
Encapsulation is a process of wrapping of data and methods in a single unit. It is achieved in
C++ language by class concept.
Combining of state and behavior in a single container is known as encapsulation. In C++
language encapsulation can be achieve using class keyword, state represents declaration of
variables on attributes and behavior represents operations in terms of method.
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the data from other methods, when
we make a data private then these data only use within the class, but these data not accessible
outside the class.
Real Life Example of Encapsulation in C++
The common example of encapsulation is Capsule. In capsule all medicine are encapsulated in
side capsule.
Benefits of encapsulation
• Provides abstraction between an object and its clients.
• Protects an object from unwanted access by clients.
Example: A bank application forbids a client to change an Account's balance
Example used Abstraction example is served.
Polymorphism in C++
The process of representing one Form in multiple forms is known as Polymorphism. Here one
form represent original form or original method always resides in base class and multiple forms
represents overridden method which resides in derived classes.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and morphs means forms. So polymorphism means many forms.
63
Real life example of Polymorphism in C++
Suppose if you are in class room that time you behave like a student, when you are in market at
that time you behave like a customer, when you at your home at that time you behave like a son
or daughter, Here one person have different-different behaviors.
Type of polymorphism
• Compile time polymorphism
• Run time polymorphism
Compile time polymorphism
In C++ programming you can achieve compile time polymorphism in two ways, which is given
below;
• Method overloading
• Method overriding
Method Overloading in C++
Whenever same method name is exiting multiple times in the same class with different number
of parameter or different order of parameters or different types of parameters is known
as method overloading. In below example method "sum()" is present in addition class with
same name but with different signature or arguments.
64
Example of method overloading:
Output:
65
File Handling in C++
File Handling concept in C++ language is used for store a data permanently in computer and
using file easily to transfer a data from one computer to another. Using file handling we can
store our data in Secondary memory (Hard disk).
Datatype Description
Fstream This is used to both read and write data from/to files
Function Operation
Example:
Closing a File
A file must be close after completion of all operation related to file. For closing file we
need close() function.
Syntax
67
put() and get() function
The function put() write a single character to the associated stream. Similarly, the function get()
reads a single character from the associated stream.
read() and write() function
These functions take two arguments. The first is the address of the variable V, and the second is
the length of that variable in bytes. The address of variable must be cast to type char * (i.e
pointer to character type).
Example:
Both ios :: app and ios :: ate take us to the end of the file when it is opened. The difference
between the two parameters is that the ios :: app allows us to add data to the end of file only,
while ios :: ate mode permits us to add data or to modify the existing data anywhere in the file.
The mode can combine two or more parameters using the bitwise OR operator (symbol |)
Example:
File pointer
Each file has two associated pointers known as the file pointers. One of them is called the input
pointer (or get pointer) and the other is called the output pointer (or put pointer). The input
68
pointer is used for reading the contents of a given file location and the output pointer is used for
writing to a given file location.
Function for manipulation of file pointer
When we want to move file pointer to desired position then use these function for manage the
file pointers.
Function Operation
fout . seekg(m, ios :: cur) go forward by m bytes from the current position
fout . seekg(-m, ios :: cur) go backward by m bytes from the current position
69
Read and Write data from/to File
Output:
70
Enter your choice (1-Read, 2-Write, 3-exit): 1
Enter roll_no: 1
Enter name: musa
Enter father name: sani
Enter your choice (1-Read, 2-Write, 3-exit): 2
Enter roll_no.: 1
roll no.: 1
stu name.: musa
father name: sani
Exception Handling in C++
The process of converting system error messages into user friendly error message is known
as Exception handling. This is one of the powerful features of C++ to handle run time error
and maintain normal flow of C++ application.
Exception
An exception is an event, which occurs during the execution of a program, which disrupts the
normal flow of the program's Instructions.
Handling the Exception
Handling the exception is nothing but converting system error message into user friendly error
message. Use Three keywords for Handling the Exception in C++ Language, they are;
1. try
2. catch
3. throw
Syntax for handling the exception
Try Block
It is one of the block in which we write the block of statements which causes executions at
run time in other words try block always contains problematic statements.
Catch block
71
It is one of the block in which we write the block of statements which will generates user
friendly error messages in other words catch block will suppose system error messages.
Example without Exception Handling
72
Complexity Analysis
The Complexity analysis is used to determine, the algorithm will take amount of resources (such
as time and space) necessary to execute it.
There are two types of complexities: 1) Time Complexity and 2) Space Complexity.
Searching Techniques
There are basically three types of searching techniques:
• Linear or sequential search
• Binary search
• Interpolation Search
Linear/ Sequential Search
Linear/Sequential searching is a searching technique to find an item from a list until the
particular item not found or list not reached at end. We start the searching from 0th index to N-1
index in a sequential manner, if particular item found, returns the position of that item otherwise
return failure status or -1.
74
Output:
Binary Search
It is special type of search work on sorted list only. During each stage of our procedure, our
search for ITEM is reduced to a restricted segment of elements in LIST array. The segment
starts from index LOW and spans to HIGH.
LIST [LOW], LIST [LOW+1], LIST [LOW+2], LIST [LOW+ 3]….. LIST[HIGH]
The ITEM to be searched is compared with the middle element LIST[MID] of segment,
where MIDobtained as:
MID = ( LOW + HIGH )/2
We assume that the LIST is sorted in ascending order. There may be three results of this
comparison:
1. If ITEM = LIST[MID], the search is successful. The location of the ITEM is LOC :=
MID.
2. If ITEM < LIST[MID], the ITEM can appear only in the first half of the list. So, the
segment is restricted by modifying HIGH = MID – 1.
3. If ITEM > LIST[MID], the ITEM can appear only in the second half of the list. So, the
segment is restricted by modifying LOW = MID + 1.
75
Initially, LOW is the start index of array, and HIGH is the last index of array.
The comparison goes on. With each comparison, low and high approaches near to each other, the
loop will continue till LOW < HIGH.
76
d. Otherwise
i. Set LOW: = MID + 1;
3. Set LOC: = NULL
4. Return
77
Output:
Example 2:
Output:
78
Difference between Linear Search and Binary Search
Linear Search Binary Search
Sorted list is not required. Sorted list is required.
It can be used in linked list implementation. It cannot be used in liked list implementation.
79
Output:
Example 2:
Output:
80
81