Unit-4.1, Notes
Unit-4.1, Notes
WHAT IS OOP?
! OOP is a powerful way to approach the task of programming.
! OOP encourages developers to decompose a problem into its constituent parts.
! Each component becomes a self-contained object that contains its own instructions
and data that relate to that object.
! So, complexity is reduced and the programmer can manage larger programs.
! All OOP languages, including C++, share three common de ning traits:
! Encapsulation
! Binds together code and data
! Polymorphism
! Allows one interface, multiple methods
! Inheritance
! Provides hierarchical classi cation
! Permits reuse of common code and data
What is C++ ?
!C++ is the C programmer‟s answer to Object-Oriented Programming (OOP).
!C++ is an enhanced version of the C language.
!C++ adds support for OOP without sacri cing any of C‟s power, elegance, or
exibility.
!C++ was invented in 1979 by Bjarne Stroustrup at Bell Laboratories in Murray
Hill, New Jersey, USA.
!The elements of a computer language do not exist in a void, separate from one
another.
!The features of C++ are highly integrated.
!Both object-oriented and non-object-oriented programs can be developed using
C++.
NAMESPACES
Using namespaces, we can create two variables or member functions having the same name.
#include <iostream>
using namespace std;
// Variable created inside namespace
fl
fi
fi
fi
namespace rst
{
int val = 500;
}
// Global variable
int val = 100;
int main()
{
// Local variable
int val = 200;
return 0;
}
• Namespaces allow us to group named entities that otherwise would have global scope into
narrower scopes, giving them namespace scope. This allows organizing the elements of
programs into di erent logical scopes referred to by names.
• Namespace is a feature added in C++ and not present in C.
• A namespace is a declarative region that provides a scope to the identi ers (names of the
types, function, variables etc) inside it.
• Multiple namespace blocks with the same name are allowed. All declarations within those
blocks are declared in the named scope.
• A namespace de nition begins with the keyword namespace followed by the namespace
name as follows:
namespace namespace_name
{
int x, y; // code declarations where
// x and y are declared in
// namespace_name's scope
}
int main()
{
// Access value function within ns1
cout << ns1::value() << '\n';
return 0;
}
namespace ns
{
// A Class in a namespace
class geek
{
public:
void display()
{
cout << "ns::geek::display()\n";
}
};
}
int main()
{
// Creating Object of geek Class
ns::geek obj;
obj.display();
return 0;
}
ns::geek::display()
Class can also be declared inside namespace and de ned outside namespace using following
syntax
namespace ns
{
// Only declaring class here
class geek;
}
int main()
{
//Creating Object of geek Class
ns::geek obj;
obj.display();
return 0;
}
// Creating a namespace
namespace ns
{
void display();
class geek
{
public:
fi
fi
fi
fi
void display();
};
}
// Driver code
int main()
{
ns::geek obj;
ns::display();
obj.display();
return 0;
}
Identi ers
The C++ identi er is a name used to identify a variable, function, class, module, or any other user-
de ned item.
• Uppercase and lowercase letters are distinct. Manpower and manpower are two di erent
identi ers in C++.
Variables
• A variable is a name given to a memory location. It is the basic unit of storage in a program.
• A variable is only a name given to a memory location, all the operations done on the variable
e ects that memory location.
• A variable name can consist of alphabets (both upper and lower case), numbers and the
underscore ‘_’ character. However, the name must not start with a number.
• The variable declaration refers to the part where a variable is rst declared or introduced
before its rst use. A variable de nition is a part where the variable is assigned a memory
location and a value. Most of the times, variable declaration and de nition are done together.
Types of variables
There are three types of variables based on the scope of variables in C++:
• Local Variables
• Instance Variables
• Static Variables
Local Variables: A variable de ned within a block or method or constructor is called local
variable.
These variable are created when the block in entered or the function is called and destroyed after
exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is declared. i.e. we
can access these variable only within that block.
Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor or block.
As instance variables are declared in a class, these variables are created when an object of the
class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access speci ers for instance variables. If we do not specify
any access speci er then the default access speci er will be used.
These variables are declared similarly as instance variables, the di erence is that static variables
are declared using the static keyword within a class outside any method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class irrespective of
how many objects we create.
Static variables are created at the start of program execution and destroyed automatically when
execution ends.
If we access the static variable like Instance variable (through an object), the compiler will show
the warning message and it won’t halt the program. The compiler will replace the object name to
class name automatically.
If we access the static variable without the class name, Compiler will automatically append the
class name.
CONSTANTS
Constants refer to xed values that do not change during the execution of a program. Like C, C+
support several kinds of literal constants. They include integers, characters, oating point
numbers and string.
Named Constant
const double CENTIMETERS_PER_INCH = 2.54; const int INCHES_PER_FOOT = 12;
Every constant has some range. The integers that are too big to t into an int will be taken as
long. Now there are various ranges that di er from unsigned to signed bits. Under the signed bit,
the range of an int varies from -128 to +127, and under the unsigned bit, int varies from 0 to 255.
De ning Constants:
In C/C++ program we can de ne constants in two ways as shown below:
• Using #de ne preprocessor directive: This directive is used to declare an alias name for
existing variable or any value. We can use this to declare a constant as shown below:
fi
fi
fi
fi
ff
ff
fi
fl
#de ne identi erName value
Literals: The values assigned to each constant variables are referred to as the literals. Generally,
both terms, constants and literals are used interchangeably. For eg, “const int = 5;“, is a constant
expression and the value 5 is referred to as constant integer literal.
#include <stdio.h>
int main()
// int constant
// Real constant
// char constant
return 0;
• The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an
example of enum declaration.
// so on.
Variables of type enum can also be de ned. They can be de ned in two ways:
// Or
#include<stdio.h>
int main()
day = Wed;
printf("%d",day);
return 0;
OUTPUT: 2
In the above example, we declared “day” as the variable and the value of “Wed” is allocated to
day, which is 2. So as a result, 2 is printed.
• Two enum names can have same value. For example, in the following C program both ‘Failed’
and ‘Freezed’ have same value 0.
#include <stdio.h>
return 0;
OUTPUT; 1,0,0
#include <stdio.h>
int main()
return 0;
• We can assign values to some name in any order. All unassigned names get value as value of
previous name plus one.
#include <stdio.h>
int main()
return 0;
OUTPUT: 1 2 5 6 10 11 12
• The value assigned to enum names must be some integral constant, i.e., the value must be in
range from minimum possible integer value to maximum possible integer value.
• All enum constants must be unique in their scope. For example, the following program fails in
compilation.
enum state {working, failed};
ADVANTAGES:
There are multiple advantages of using enum over macro when many related named
constants have integral values.
a) Enums follow scope rules.
b) Enum variables are automatically assigned values.
OPERATORS
An operator is a symbol which represents a particular operation that can be performed on data.
An operand is the object on which an operation is performed.
C++ has many built-in operators and can be classi ed into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
fi
4. Bitwise Operators
5. Assignment Operators
1. Arithmetic Operators:
a) Unary Operators: Operators that operate or work with a single operand are unary
operators. For example: Increment(++) and Decrement(–) Operators
b) Binary Operators: Operators that operate or work with two operands are binary
operators. For example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators
2. Relational Operators:These are used for the comparison of the values of two operands. For
example, checking if one operand is equal to the other operand or not, an operand is greater than
the other operand or not, etc. Some of the relational operators are (==, >= , <= )(See this article for
more reference).
3. Logical Operators:
For example, the logical AND represented as ‘&&’ operator in C or C++ returns true when both the
conditions under consideration are satis ed. Otherwise, it returns false. Therefore, a && b returns
true when both a and b are true (i.e. non-zero)
4. Bitwise Operators:
The Bitwise operators are used to perform bit-level operations on the operands. The operators are
rst converted to bit-level and then the calculation is performed on the operands. The
mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
bit-level for faster processing. For example, the bitwise AND represented as & operator in C or C+
+ takes two numbers as operands and does AND on every bit of two numbers. The result of AND
is 1 only if both bits are 1.
5. Assignment Operators:
Assignment operators are used to assigning 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.
d. “*=”: This operator is a combination of ‘*’ and ‘=’ operators. This operator rst multiplies
the current value of the variable on left to the value on the right and then assigns the result
to the variable on the left.
fi
ff
fi
fi
fi
fi
e. “/=”: This operator is a combination of ‘/’ and ‘=’ operators. This operator rst divides
the current value of the variable on left by the value on the right and then assigns the result
to the variable on the left. Other Operators
Global scope: visibility of a variable to all functions of a program Scope resolution operator in
“::” .
This is used to access global variables if same variables are declared as local and global.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid loss of data.
All the data types of the variables are upgraded to the data type of the variable with largest data
type.
bool -> char -> short int -> int -> unsigned int ->long -> unsigned -> long long -> oat -> double->
long double
It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and over ow can occur (when long long is implicitly converted
to oat).
#include <iostream>
int main()
// value of 'a' is 97
x = x + y;
oat z = x + 1.0;
return 0;
OUTPUT: x=107
y=a
z=108
Explicit Type Conversion– This process is also called type casting and it is user-de ned. Here
the user can typecast the result to make it of a particular data type.
fl
fl
fl
fl
fl
fi
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly de ning the required type in front of the
expression in parenthesis. This can be also considered as forceful casting.
where type indicates the data type to which the nal result is converted.
#include <iostream>
int main()
double x = 1.2;
OUTPUT: SUM=2
1. This is done to take advantage of certain features of type hierarchies or type representations.
CONTROL STUCTURES
There are three types of control structures available in C++
The if keyword is used to execute a statement or block only if a condition is ful lled. Its form is:
if (condition) statement
Where condition is the expression that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the program continues right after
this conditional structure.
For example, the following code fragment prints x is 100 only if the value stored in the x variable is
indeed 100:
fi
fi
ff
fi
1 if (x == 100)
2 cout << "x is
100";
If we want more than a single statement to be executed in case that the condition is true we can
specify a block using braces { }:
1 if (x == 100)
2{
3 cout << "x is
4 ";
5 cout << x;
}
We can additionally specify what we want to happen if the condition is not ful lled by using the
keyword else. Its form used in conjunction with if is:
For example:
1 if (x == 100)
2 cout << "x is 100";
3 else
4 cout << "x is not
100";
prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it
prints out x is not 100.
The if + else structures can be concatenated with the intention of verifying a range of values. The
following example shows its use telling if the value currently stored in x is positive, negative or
none of them (i.e. zero):
1 if (x > 0)
2 cout << "x is
3 positive";
4 else if (x < 0)
5 cout << "x is
6 negative";
else
cout << "x is 0";
Remember that in case that we want more than a single statement to be executed, we must
group them in a block by enclosing them in braces { }.
fi
Iteration structures (loops)
Loops have as purpose to repeat a statement a certain number of times or while a condition is
ful lled.
and its functionality is simply to repeat statement while the condition set in expression is true.
The whole process of the previous program can be interpreted according to the following script
(beginning in main):
The while condition is checked (n>0). At this point there are two possibilities:
* condition is true: statement is executed (to step 3)
* condition is false: ignore statement and continue after it (to step 5)
fi
fi
Execute statement:
cout << n << ", ";
--n;
(prints the value of n on the screen and decreases n by 1)
Continue the program right after the block: print FIRE! and end program.
When creating a while-loop, we must always consider that it has to end at some point, therefore
we must provide within the block some method to force the condition to become false at some
point, otherwise the loop will continue looping forever. In this case we have included --n; that
decreases the value of the variable that is being evaluated in the condition (n) by one - this will
eventually make the condition (n>0) to become false after a certain number of loop iterations: to
be more speci c, when n becomes 0, that is where our while-loop and our countdown end.
Of course this is such a simple action for our computer that the whole countdown is performed
instantly without any practical delay between numbers.
Its functionality is exactly the same as the while loop, except that condition in the do-while loop is
evaluated after the execution of statement instead of before, granting at least one execution of
statement even if condition is never ful lled. For example, the following example program echoes
any number you enter until you enter 0.
and its main function is to repeat statement while condition remains true, like the while loop. But
in addition, the for loop provides speci c locations to contain an initialization statement and an
increase statement. So this loop is specially designed to perform a repetitive action with a counter
which is initialized and increased on each iteration.
initialization is executed. Generally it is an initial value setting for a counter variable. This is
executed only once.
condition is checked. If it is true the loop continues, otherwise the loop ends and statement is
skipped (not executed).
statement is executed. As usual, it can be either a single statement or a block enclosed in braces
{ }.
nally, whatever is speci ed in the increase eld is executed and the loop gets back to step 2.
The initialization and increase elds are optional. They can remain empty, but in all cases the
semicolon signs between them must be written. For example we could write: for (;n<10;) if we
wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an
increase eld but no initialization (maybe because the variable was already initialized before).
fi
fi
fi
fi
fi
fi
Optionally, using the comma operator (,) we can specify more than one expression in any of the
elds included in a for loop, like in initialization, for example. The comma operator (,) is an
expression separator, it serves to separate more than one expression where only one is generally
expected. For example, suppose that we wanted to initialize more than one variable in our loop:
This loop will execute for 50 times if neither n or i are modi ed within the loop:
n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is
increased by one and i decreased by one, the loop's condition will become false after the 50th
loop, when both n and i will be equal to 50.
Jump statements.
break statement
Using break we can leave a loop even if the condition for its end is not ful lled. It can be used to
end an in nite loop, or to force it to end before its natural end. For example, we are going to stop
the count down before its natural end (maybe because of an engine check failure?):
1 // break loop example 10, 9, 8, 7, 6, 5, 4, 3,
2 countdown aborted!
3 #include <iostream>
4 using namespace std;
5
6 int main ()
7 { E
8 int n; di
9 for (n=10; n>0; n--) t
1 { &
0 cout << n << ", "; R
1 if (n==3) u
1 { n
1 cout << "countdown
2 aborted!";
1 break;
3 }
1 }
4 return 0;
1 }
fi
fi
fi
fi
continue statement: The continue statement causes the program to skip the rest of the loop in
the current iteration as if the end of the statement block had been reached, causing it to jump to
the start of the following iteration. For example, we are going to skip the number 5 in our
countdown:
goto statement: goto allows to make an absolute jump to another point in the program. You
should use this feature with caution since its execution causes an unconditional jump ignoring any
type of nesting limitations.
The destination point is identi ed by a label, which is then used as an argument for the goto
statement. A label is made of a valid identi er followed by a colon (:).
Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming fans may nd for it. For example, here
is our countdown loop using goto:
The purpose of exit is to terminate the current program with a speci c exit code. Its prototype is:
The exitcode is used by some operating systems and may be used by calling programs. By
convention, an exit code of 0 means that the program nished normally and any other value
means that some error or unexpected results happened.
The syntax of the switch statement is a bit peculiar. Its objective is to check several possible
constant values for an expression. Something similar to what we did at the beginning of this
section with the concatenation of several if and else if instructions. Its form is the following:
switch (expression)
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
default:
It works in the following way: switch evaluates expression and checks if it is equivalent to
constant1, if it is, it executes group of statements 1 until it nds the break statement. When it
nds this break statement the program jumps to the end of the switch selective structure.
If expression was not equal to constant1 it will be checked against constant2. If it is equal to this,
it will execute group of statements 2 until a break keyword is found, and then will jump to the end
of the switch selective structure.
fi
fi
fi
fi
fi
Finally, if the value of expression did not match any of the previously speci ed constants (you can
include as many case labels as values you want to check), the program will execute the
statements included after the default: label, if it exists (since it is optional).
The switch statement is a bit peculiar within the C++ language because it uses labels instead of
blocks. This forces us to put break statements after the group of statements that we want to be
executed for a speci c condition. Otherwise the remainder statements -including those
corresponding to other labels- will also be executed until the end of the switch selective block or
a break statement is reached.
For example, if we did not include a break statement after the rst group for case one, the
program will not automatically jump to the end of the switch selective block and it would continue
executing the rest of statements until it reaches either a break instruction or the end of the switch
selective block. This makes it unnecessary to include braces { } surrounding the statements for
each of the cases, and it can also be useful to execute the same block of instructions for di erent
possible values for the expression being evaluated. For example:
1 switch (x) {
2 case 1:
3 case 2:
4 case 3:
5 cout << "x is 1, 2 or 3";
6 break;
7 default:
8 cout << "x is not 1, 2 nor
9 3";
}
Notice that switch can only be used to compare an expression against constants. Therefore we
cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):)
because they are not valid C++ constants.
fi
fi
fi
ff