Unit4.Notes.OOSD
Unit4.Notes.OOSD
Object-Oriented Programming
C++ fully supports object-oriented programming, including the four pillars of object-oriented
development −
Encapsulation
Data hiding
Inheritance
Polymorphism
#include <iostream>
using namespace std;
C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or any other
user-defined item.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores, and digits (0 to 9).
Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
C++ Keywords
The following list shows the reserved words in C++. These reserved words may not be used
as constant or variable or any other identifier names.
In C++, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
bool - stores values with two states: true or false
To create a variable, you must specify the type and assign it a value:
Syntax
type variable = value;
Example
Create a variable called myNum of type int and assign it the value 15:
CONSTANT
Constants refer to fixed values that the program may not alter during its execution. These fixed values
are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal.
Defining Constants
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
int main() {
int area;
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
int area;
Opeartors
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.
C++ language is rich in built-in operators and provides the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Show Examples
Operator Description Example
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10
and variable B holds 20 then −
Show Examples
== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not. If the values are not (A != B)
equal, then the condition becomes true. is true.
!= Checks if the values of two operands are equal or not. If the values are not (A != B)
equal, then the condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right operand. (A > B)
If yes, then the condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right operand. If (A < B)
yes, then the condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand. If yes, then the condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value of right (A <= B)
operand. If yes, then the condition becomes true. is true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1
and variable B holds 0, then −
Show Examples
&& Called Logical AND operator. If both the operands are non-zero, then the (A &&
condition becomes true. B) is
false.
! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it B) is
false. true.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows −
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples
= Simple assignment operator. Assigns values from right side operands to C=A+
left side operand B will
assign the
value of
A + B to
C
+= Add AND assignment operator. It adds the right operand to the left C += A is
operand and assign the result to the left operand. equivalent
to C = C
+A
-= Subtract AND assignment operator. It subtracts the right operand from the C -= A is
left operand and assigns the result to the left operand. equivalent
to C = C -
A
*= Multiply AND assignment operator. It multiplies the right operand with the C *= A is
left operand and assigns the result to the left operand. equivalent
to C = C
*A
/= Divide AND assignment operator. It divides the left operand with the right C /= A is
operand and assigns the result to the left operand. equivalent
to C = C /
A
Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.
Show Examples
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
Data types are used to tell the variables the type of data it can store. Whenever a variable is defined
in C++, the compiler allocates some memory for that variable based on the data-type with which it is
declared. Every data type requires a different amount of memory.
1. Primitive Data Types: These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char , float, bool etc. Primitive data types
available in C++ are:
Integer
Character
Boolean
Floating Point
Double Floating Point
2. Derived Data Types: The data-types that are derived from the primitive or built-in datatypes are
referred to as Derived Data Types. These can be of four types namely:
Function
Array
Pointer
Reference
3. Abstract or User-Defined Data Types: These data types are defined by user itself. Like,
defining a class in C++ or a structure. C++ provides the following user-defined datatypes:
Class
Structure
Union
Enumeration
Typedef defined DataType
Control statements enable us to specify the flow of program control; ie, the
order in which the instructions in a program must be executed.
.
Types of Control Statements in C++
1. Decision making statement
2. Looping statement
3. Jumping statement
The if-else statement is used to carry out a logical test and then take one
actions depending on the outcome of the test (ie, whether the outcome is
true or false).
Syntax:
if (condition)
statements
else
{The following program checks whether the entered number is positive or negative.
#include<iostream.h>
int main( )
int a;
cout<<"n Enter anumber:";
cin>>a;
if(a>0)
else
}
It is also possible to embed or to nest if-else statements one within the other.
Nesting is useful in situations where one of several different courses of action
need to be selected.
return 0;
int main( )
{
int a, b,c;
a=6,b= 5, c=10;
if(a>b)
{
if(b>c)
{
cout<<"n a is Greatest is: ";
}
else if(c>a)
{
cout<<"n c is Greatest is: ";
}
}
else if(b>c) //outermost if-else block
{
cout<<"n b is Greatest is: ";
}
else
{
cout<< “ c Greatest is: " ;
}
return 0;
}
Syntax:
switch (expression)
{
case 1:
code segment1;
break;
case 2:
code segment2;
break;
.
.
.
case N:
code segmentN;
break;
Example: a program to print the day of the week.
default:
#include<iostream.h>
default code segment;
int main( )
}
{
int day;
cin>>day;
switch(day)
{
case 1:
cout<<"Sunday
cout<<"Wednesday";
break;
case 5:
cout<<"Thursday";
break;
case 6:
cout<<"Friday";
break;
case 7:
cout<<"Saturday";
break;
default:
cout<<"Invalid choice”;
}
return 0;
In an entry control loop in C++, a condition is checked before executing the body of a loop. It is
also called as a pre-checking loop.
In an exit controlled loop, a condition is checked after executing the body of a loop. It is also
called as a post-checking loop.
Sample Loop
Sr. Loop
Description
No. Type
While In while loop, a condition is evaluated before processing a body of the loop. If a
1.
Loop condition is true then and only then the body of a loop is executed.
Do-While In a do…while loop, the condition is always executed after the body of a loop. It is
2.
Loop also called an exit-controlled loop.
In a for loop, the initial value is performed only once, then the condition tests and
3. For Loop compares the counter to a fixed value after each iteration, stopping the for loop
when false is returned.
While Loop in C++
Syntax:
while (condition)
{
statements;
}
It is an entry-controlled loop. In while loop, a condition is evaluated before
processing a body of the loop. If a condition is true then and only then the
body of a loop is executed.
#include<iostream.h>
#include<conio.h> int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
cout<<num;
num++; //incrementing operation
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Do-While loop
A do…while loop in C++ is similar to the while loop except that the condition is
always executed after the body of a loop. It is also called an exit-controlled
loop.
Syntax
do
{
statements
} while (expression);
The following loop program in C++ illustrates the working of a do-while 2:
#include<iostream.h>
#include<conio.h> int main()
{
int num=1; //initializing the variable
do //do-while loop
{
cout<<2*num;
num++; //incrementing operation
}while(num<=10);
return 0;
}
Output:
2
4
6
8
10
12
14
16
18
For loop
A for loop is a more efficient loop structure in ‘C++’ programming. The general
structure of for loop syntax in C++ is as follows:
Syntax o:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
Following program illustrates the for loop in C++ programming
example:
#include<iostream.h
> int main()
{
int number;
for(number=1;number<=10;number++) //for loop
to print 1-10 numbers
{
cout<<"number”; //to print
the number
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
.
Break Statement
The break statement is used mainly in in the switch statement. It is also useful
for immediately stopping a loop.
Continue Statement
When you want to skip to the next iteration but remain in the loop, you should
use the continue statement.
For example:
{
int nb = 7;
while (nb > 0)
{
nb--;
if (nb == 5)
continue;
cout<<" nb”;
}}
Output:
6
4
3
2
1
Typecasting is making a variable of one type, such as an int, act like another type, a
char, for one single operation. To typecast something, simply put the type of
variable you want the actual variable to act as inside parentheses in front of the
actual variable. (char)a will make 'a' function as a char.
For example:
1
2 #include <iostream>
3
4 using namespace std;
5
6 int main()
7 {
cout<< (char)65 <<"\n";/
}
Consider a situation, when we have two persons with the same name, Zara, in
the same class. Whenever we need to differentiate them definitely we would
have to use some additional information along with their name, like either the
area, if they live in different area or their mother’s or father’s name, etc.
Same situation can arise in your C++ applications. For example, you might be
writing some code that has a function called xyz() and there is another library
available which is also having same function xyz(). Now the compiler has no
way of knowing which version of xyz() function you are referring to within
your code.
Defining a Namespace
namespace namespace_name {
// code declarations
}
Let us see how namespace scope the entities including variable and
functions –
#include <iostream>
int main () {
// Calls function from first name space.
first_space::func();
If we compile and run above code, this would produce the following result −
Inside first_space
Inside second_space
int main()
{
enum week day;
day = Wed;
cout<<”day”;
return 0;
}
Syntax of Function
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
Types of function
We have two types of function in C++
1) Built-in functions
2) User-defined functions
1) Built-in 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.
The functions that are defined by user is called user defined function.
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
int main(){
/* In this case a value is passed as
* 1 and b and c values are taken from
* default arguments.
*/
cout<<sum(1)<<endl;
31
23
6
Inline Function
C++ inline function is powerful concept that is commonly used with classes. If a function is
inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.
Following is an example, which makes use of inline function to return max of two
numbers −
#include <iostream>
using namespace std;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
Let's understand call by value and call by reference in C++ language one by one.
Call by value in C++
In call by value, original value is not modified.
Let's try to understand the concept of call by value in C++ language by the example
given below:
1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }
Output:
Here, address of the value is passed in the function, so actual and formal arguments
share the same address space. Hence, value changed inside the function, is reflected
inside as well as outside the function.
Note: To understand the call by reference, you must have the basic knowledge of
pointers.
Let's try to understand the concept of call by reference in C++ language by the
example given below:
1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }
Output:
2 Changes made inside the function is Changes made inside the function is
not reflected on other functions reflected outside the function also
3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
In C++, inline may be defined Whereas the macro is all the time
either inside the class or defined at the beginning of the
5. outside the class. program.
#include <iostream>
void print(int i) {
void print(double f) {
int main() {
print(10);
print(10.10);
print("ten");
return 0;
Output:
Here is int 10
Here is float 10.1
Here is char* ten