Professional Documents
Culture Documents
Introduction to OOP :
Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects", which can contain data and code: data in the form of fields (often known
as attributes or properties), and code, in the form of procedures (often known as methods).
The main aim of OOP is to bind together the data and the functions that operate on them so that
no other part of the code can access this data except that function.
Classes are user-defined data types that act as the blueprint for individual objects, attributes
and methods.
Objects are instances of a class created with specifically defined data. Objects can
correspond to real-world objects or an abstract entity.
Methods are functions that are defined inside a class that describe the behaviors of an object.
Attributes are defined in the class template and represent the state of an object. Objects will
have data stored in the attributes field.
1
By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
Message passing techniques is used for communication between objects .
Application of OOPs in C++ (10 marks)
class
objects
encapsulation
polymorphism
inheritance
abstraction
2
Class − A class is a data-type that has its own members i.e. data members and member functions.
It is the blueprint for an object in object oriented programming language.
It is the basic building block of object oriented programming in c++.
The members of a class are accessed in programming language by creating an instance of the
class.
Some important properties of class are −
Class is a user-defined data-type.
A class contains members like data members and member functions.
Data members are variables of the class.
Member functions are the methods that are used to manipulate data members.
Data members define the properties of the class whereas the member functions define the
behaviour of the class.
A class can have multiple objects which have properties and behaviour that in common for all
of them.
Syntax
class class_name
{
data_type data_name;
return_type method_name(parameters);
}
Object − An object is an instance of a class. It is an entity with characteristics and behaviour that
are used in the object oriented programming. An object is the entity that is created to allocate
memory. A class when defined does not have memory chunk itself which will be allocated as
soon as objects are created.
Syntax
class_name object_name;
3
Operator overloading In operator overloading , operator can have multiple behaviour in
different instances of usage.
Function overloading Functions with the same name that can do multiple types of tasks based
on some condition.
Inheritance it is the capability of a class to inherit or derive properties or characteristics other
class. it is very important and object oriented program as it allows reusability i.e. using a method
defined in another class by using inheritance. The class that derives properties from other class is
known as child class or subclass and the class from which the properties are inherited is base
class or parent clas
Abstraction Data abstraction or Data Hiding is the concept of hiding data and showing only
relevant data to the final user. It is also an important part of object oriented programing.
Main Function: The main () is a startup function that starts the execution of a c++ program. All
C++ statements that need to be executed are written within main ( ).
.
Eg:
4
#include <iostream.h>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}
It copies and pastes the entire text of the file, specified between the angle brackets, into
the source code.
The file <iostream> input-output streams is a standard file that comes with the C++
compiler.
It contains code for displaying and getting an input from the user.
Namespace permits grouping of various entities like classes, objects, functions and
various C++ tokens, etc., under a single name.
UNIT-II
Tokens :
A token is the smallest element of a program that is meaningful to the compiler.
Different kinds of Tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
2.Identifiers:
.
Rules to be followed to name c++ identifiers:
They must begin with a letter or underscore(_).
They must consist of only letters, digits, or underscore. No other special character is
allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
3.Constants:
Constants refer to fixed values.
They are also called literals.
Constant values can not be modified by the program once they are defined.
Constants may belong to any of the data type
4.Strings:
A String is an array of characters ended with a null character (\0).
Null character indicates the end of the string.
Strings are always enclosed in double-quotes.
A character is enclosed in single quotes in C and C++.
Declarations of String:
char string[20] = {g, e, e, k, s, f, o, r, g, e, e, k , s , \0 };
char string[20] = geeksforgeeks;
char string [] = geeksforgeeks;
5. Special Symbols:
The following special symbols are used in C++ having some special meaning and thus, cannot
be used for some other purpose.[] () {}, ; * = #
Brackets[ ]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
Comma (, ): It is used to separate more than one statements like for separating parameters
in function calls.
Colon(:): It is an operator that essentially invokes something called an initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity. Thats why each individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable.
Assignment operator(=): It is used to assign values.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
6.Operators in C++ :
Operators are symbols that trigger an action when applied to C++ variables and other
objects.
The data items on which operators act upon are called operands.
Arithmetic Operators
8
Relational Operators
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less than (A < B) is true.
the value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.
<= Checks if the value of left operand is less than (A <= B) is true.
or equal to the value of right operand, if yes
then condition becomes true.
Logical Operators
9
&& Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then condition becomes
true.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^
are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
10
A^B = 0011 0001
~A = 1100 0011
| Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is 0011 1101
either operand.
~ Binary Ones Complement Operator is unary (~A ) will give -61 which is 1100 0011 in 2's
and has the effect of 'flipping' bits. complement form due to a signed binary
number.
Assignment Operators
= Simple assignment operator, Assigns values from right side operands to C = A + B will assign value of
left side operand. A + B into C
11
+= Add AND assignment operator, It adds right operand to the left operand C += A is equivalent to C = C
and assign the result to left operand. +A
-= Subtract AND assignment operator, It subtracts right operand from the C -= A is equivalent to C = C
left operand and assign the result to left operand. -A
*= Multiply AND assignment operator, It multiplies right operand with the C *= A is equivalent to C = C
left operand and assign the result to left operand. *A
/= Divide AND assignment operator, It divides left operand with the right C /= A is equivalent to C = C /
operand and assign the result to left operand. A
Miscellaneous Operators
The following table lists some other operators that C++ supports.
1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where a is integer, and will
return 4.
2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of
Y.
3 ,
Comma operator causes a sequence of operations to be performed. The value of the entire comma
expression is the value of the last expression of the comma-separated list.
12
4 . (dot) and -> (arrow)
Member operators are used to reference individual members of classes, structures, and unions.
5 Cast
Casting operators convert one data type to another. For example, int(2.2000) would return 2.
6 &
Pointer operator & returns the address of a variable. For example &a; will give actual address of
the variable.
7 *
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.
Compiler allocates some memory for that variable based on the data-type with which it is
declared.
13
Data types in C++ is mainly divided into three types:
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
Valueless or Void
Wide Character
Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of
memory space and ranges from -2147483648 to 2147483647.
Character: Character data type is used for storing characters. Keyword used for character
data type is char. Characters typically requires 1 byte of memory space and ranges from -128
to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable
can store either true or false. Keyword used for boolean data type is bool.
Floating Point: Floating Point data type is used for storing single precision floating point
values or decimal values. Keyword used for floating point data type is float. Float variables
14
typically requires 4 byte of memory space.
Double Floating Point: Double Floating Point data type is used for storing double precision
floating point values or decimal values. Keyword used for double floating point data type
is double. Double variables typically requires 8 byte of memory space.
void: Void means without any value. void datatype represents a valueless entity. Void data
type is used for those function which does not returns a value.
Wide Character: Wide character data type is also a character data type but this data type has
size greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4
bytes long.
3.User-DefinedDataTypes
Various user-defined data types provided by C++ are structures, unions,
enumerations and classes.
15
STRUCTURE
Structure is a collection of variables (can be of different data types) under a single name.
structure variable
struct person
{
char name[50];
int no;
float salary;
};
int x,y,z;
int main()
{
struct person person1, person2, p[20];
return 0;
}
16
UNION
● Union allocates one common storage space for all its members
● We can access only one member of union at a time
● Many union variables can be created in a program and memory will be allocated for each
union variable separately.
EXAMPLE:
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
Class − A class is a data-type that has its own members i.e. data members and member functions.
It is the blueprint for an object in object oriented programming language.
It is the basic building block of object oriented programming in c++.
The members of a class are accessed in programming language by creating an instance of the
class.
Some important properties of class are −
Class is a user-defined data-type.
A class contains members like data members and member functions.
17
Data members are variables of the class.
Member functions are the methods that are used to manipulate data members.
Data members define the properties of the class whereas the member functions define the
behaviour of the class.
A class can have multiple objects which have properties and behaviour that in common for all of
them.
Syntax
class class_name {
data_type data_name;
return_type method_name(parameters);
}
C++ offers a new user-defined data type known as class, which forms the basis of object-
oriented programming.
A class acts as a template which defines the data and functions that are included in an object of
a class.
Classes are declared using the keyword class. Once a class has been declared, its object can be
easily created.
Enumeration: An enumeration is a set of named integer constants that specify all the
permissible values that can be assigned to enumeration variables.
These set of permissible values are known as enumerators.
Eg:
enum country {US, UN, India, China}; // declaring an
// enum type
typedef
C++ provides a typedef feature that allows to define new data type names for existing
data types that may be built-in, derived or user-defined data types.
Once the new name has been defined, variables can be declared using this new name.
Eg :
typedef int integer;
18
In this declaration, a new name integer is given to the data type into This new name now can be
used to declare integer variables as shown here.
integer i, j, k;
A storage class defines the scope (visibility) and life-time of variables and/or functions within a
C++ Program.
These specifiers precede the type that they modify.
There are following storage classes, which can be used in a C++ Program
auto
register
19
static
extern
mutable
The auto storage class is the default storage class for all local variables.
int mount;
auto int month;
The register storage class is used to define local variables that should be stored in a register
instead of RAM.
This means that the variable has a maximum size equal to the register size (and can't have the
unary '&' operator applied to it .
The register should only be used for variables that require quick access such as counters.
It should also be noted that defining 'register' does not mean that the variable will be stored in a
register.
static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program.
In C++, when static is used on a class data member, it causes only one copy of that member to
be shared by all objects of its class.
#include <iostream.h>
// Function declaration
void func(void);
main() {
while(count--) {
func();
20
}
return 0;
}
// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
cout << "i is " << i ;
cout << " and count is " << count;
cout<<endl;
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
The extern storage class is used to give a reference of a global variable that is visible to all the
program files.
When you use 'extern' the variable cannot be initialized as all it does is point the variable name
at a storage location that has been previously defined.
The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions as explained below.
#include <iostream>
void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}
C++ Manipulators
Manipulators are operators used in C++ for formatting output. The data is manipulated
by the programmers choice of display.
endl Manipulator:
This manipulator has the same functionality as the n newline character.
For example:
1. cout << "Exforsys" << endl;
2. cout << "Training";
Exforsys
Training
setw Manipulator:
This manipulator sets the minimum field width on output.
Syntax:
setw(x)
Here setw causes the number or string that follows it to be printed within a field of x
characters wide and x is the argument set in setw manipulator.
The header file that must be included while using setw manipulator is .
Example:
#include <iostream>
#include <iomanip>
void main( )
{
int x1=123,x2= 234, x3=789;
cout << setw(8) << "Exforsys" << setw(20) << "Values" << endl
22
<< setw(8) << "test123" << setw(20)<< x1 << endl
<< setw(8) << "exam234" << setw(20)<< x2 << endl
<< setw(8) << "result789" << setw(20)<< x3 << endl;
}
Output:
test 123
exam 234
result 789
setfill Manipulator:
This is used after setw manipulator.
If a value does not entirely fill a field, then the character specified in the setfill argument
of the manipulator is used for filling the fields.
Example:
#include <iostream>
#include <iomanip>
void main()
{
cout << setw(15) << setfill('%') << 99 << 97 << endl;
}
Output
%%%%%%%%%%%9997
setprecision Manipulator:
The setprecision Manipulator is used with floating point numbers.
It is used to set the number of digits printed to the right of the decimal point.
This may be used in two forms:
1. fixed
23
2. scientific
These two forms are used when the keywords fixed or scientific are appropriately used
before the setprecision manipulator.
The keyword fixed before the setprecision manipulator prints the floating point number in
fixed notation.
The keyword scientific, before the setprecision manipulator, prints the floating point
number in scientific notation.
Example:
#include <iostream>
#include <iomanip>
void main( )
{
float x = 0.1;
cout << fixed << setprecision(3) << x << endl;
cout << scientific << x << endl;
}
Output:
0.100
1.000e-001
The first cout statement contains fixed notation and the setprecision contains argument 3.
This means that three digits after the decimal point and in fixed notation will output the
first cout statement as 0.100. The second cout produces the output in scientific notation.
The default value is used since no setprecision value is provided.
EXPRESSION IN C++
24
Expression: An expression is a combination of operators, constants and variables. An
expression may consist of one or more operands, and zero or more operators to produce a
value.
Types of Expressions:
Expressions may be of the following types:
Constant expressions: Constant Expressions consists of only constant values. A constant
value is one that doesnt change.
Examples:
5, 10 + 5 / 6.0, 'x
Integral expressions: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.
Floating expressions: Float Expressions are which produce floating point results after
implementing all the automatic and explicit type conversions.
Examples:
x + y, 10.75
where x and y are floating point variables.
Relational expressions: Relational Expressions yield results of type bool which takes a
value true or false. When arithmetic expressions are used on either side of a relational
operator, they will be evaluated first and then the results compared. Relational expressions
are also known as Boolean expressions.
Examples:
x <= y, x + y > 2
25
Logical expressions: Logical Expressions combine two or more relational expressions and
produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5
Pointer expressions: Pointer Expressions produce address values.
Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are
basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.
Control structures
In C++, control flow statements are used to alter, redirect, or to control the flow of program
execution based on the application logic.
Selection statements
Iteration statements
26
Jump statements
In C++, when we want to execute a block of code when if condition is true and another block of
code when if condition is false, In such a case we use if
else statement.
27
Syntax
1 if(condition){
2 // statements
3 } else {
4 // statements
5}
Here, Condition is a Boolean expression that results in either True or False, if it results
in True then statements inside if body are executed, if it results in False then statements inside
else body are executed.
#include <iostream.h>
int main()
int a = 10;
int b = 20;
28
cout<<" Finding bigger ";
if(a > b)
}
else
}
return 0;
}
Output:-
Finding Bigger
B is greater than a
29
Syntax:-
switch(expression)
{
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
break;
}
30
C++ Iteration Statements
In C++, Iteration statements are used to execute the block of code repeatedly for a specified
number of times or until it meets a specified condition. Iteration statements are commonly
known as loops or looping statements.
In C++, we have following iteration statements available-
for Loop
The for loop is used when we want to execute block of code known times. In C++, basic for loop
is similar as it is in C. The for loop takes a variable as iterator and assign it with an initial value,
and iterate through the loop body as long as the test condition is true. Once the loop statements
are executed for current iteration, the iterator is updated with new value and if the test condition
is still valid, we loop another time. When test condition return a false value, the for loop is
ended.
Syntax
for(Initialization; Condition; incr/decr)
{
// loop body
}
31
#include <iostream>
using namespace std;
int main()
{
cout<< C++ for loop";
for(int ctr=1;ctr<=5;ctr++){
cout<<"\n"<<ctr;
}
return 0;
}
While Loop
The while loop will execute a block of statement as long as a test expression is true.
While loop is useful when the number of iterations can not be predicted beforehand. The while
loop evaluates test expression at beginning of each pass.
32
Syntax
while(condition)
{
// loop body
}
Eg:
#include <iostream>
using namespace std;
int main()
{
int ctr =1;
int maxCtr =5;
cout<<" C++ while loop";
while(ctr<=maxCtr){
cout<<"\n"<<ctr;
ctr = ctr+1;
}
return 0;
33
}
do while Loop
The do
while loop executes block of statements inside loop body first and then test the
condition for next iteration and executes next only if condition is true. The do
while loop is
much similar to C++ while loop with one major difference, in do
while loop block of statements
inside loop body executes at least once.
Syntax
do{
// loop body
} while(condition);
Here, loop executes block of statements inside loop body first and then test
the condition provided along with while keyword for next iteration and executes next only
if condition is true. Condition is a Boolean expression that results in either True or False, if it
results in True then statements inside loop body are executed and condition is evaluated again.
This process is repeated until the condition is evaluated to False. If the condition results
in False then loop is terminated and control is transferred to next statement.
#include <iostream>
using namespace std;
34
int main()
{
int ctr =1;
int maxCtr =5;
cout<<"W3Adda - C++ do while loop";
do{
cout<<"\n Hello World! Value IS : "<<ctr;
ctr = ctr+1;
}while(ctr<=maxCtr);
return 0;
}
Continue Statement
In C++, the continue statement gives you way to skip over the current iteration of any loop.
When a continue statement is encountered in the loop, the rest of statements in the loop body for
current iteration and returns the program execution to the very first statement in the loop body. It
does not terminates the loop rather continues with the next iteration.
#include <iostream>
using namespace std;
int main()
{
35
int ctr = 0;
cout<<" C++ Continue Statement";
while(ctr < 10)
{
ctr = ctr + 1;
if(ctr = = 5)
{
cout<<"\n5 is skipped";
continue;
}
cout<<"\nNumber is "<<ctr;
}
cout<<"\nOut of while loop";
return 0;
}
goto statement
In C++, goto statement is used to alter the normal execution of a program and transfer control to
a labeled statement in the same program. In a C++ program we can have multiple goto and label
statements, the goto statement is followed by a label name. Label is an identifier, which can be
any plain text and can be set anywhere in a C++ program above or below to goto statement.
When a goto statement is encountered, compiler transfers the control to a label: specified with
goto statement and begin execution from there.
Syntax:
goto label;
#include <iostream>
using namespace std;
int main()
{
int age;
cout<<" C++ goto Statement";
election:
cout<<"\nEnter your age :";
cin>>age;
Break Statement
In C++, break statement inside any loop gives you way to break or terminate the execution of
loop containing it, and transfers the execution to the next statement following the loop. It is
almost always used with if..else construct.
#include <iostream>
using namespace std;
int main()
{
37
int count = 0;
cout<<" C++ Break Statement";
while(count <= 10){
count = count + 1;
if(count == 5){
break;
}
cout<<"\nInside loop "<<count;
}
cout<<"\nOut of while loop";
return 0;
}
UNIT -3
C++ Functions
A function is a group of statements that together perform a task. Every C++ program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
A function is known with various names like a method or a sub-routine or a procedure etc.
Defining a Function
38
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that define what
the function does.
Example
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file
calling the function.
Calling a Function
// function declaration
int max(int num1, int num2);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
return result;
}
Output :
40
C++ function call by reference
The call by reference method of passing arguments to a function copies the reference of an
argument into the formal parameter. Inside the function, the reference is used to access the
actual argument used in the call. The changes made to the parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the functions just like any other
value.
// function definition to swap the values.
void swap(int &x, int &y) {
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
When a function returns a reference, it returns an implicit pointer to its return value. This way, a
function can be used on the left side of an assignment statement.
include <iostream>
#include <ctime>
When the above code is compiled together and executed, it produces the following result −
Value before change
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
42
vals[3] = 24.1
vals[4] = 50
Value after change
vals[0] = 10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
vals[4] = 50
syntax :
inline return-type function-name(parameters)
{
// function code
}
Eg:
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
} //Output: The cube of 3 is: 27
43
5) Inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function call preamble and return.
C++ Recursion
When function is called within the same function, it is known as recursion in C++. The function
which calls the same function, is known as recursive function.
When any function is called from main(), the memory is allocated to it on the stack. A
recursive function calls itself, the memory for a called function is allocated on top of memory
allocated to calling function and different copy of local variables is created for each function
call. When the base case is reached, the function returns its value to the function by whom it is
called and memory is de-allocated and the process continues.
Syntax
returntype recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion(); //calling recursive function
}
Eg:
#include <stdio.h>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
44
Factorial of 12 is 479001600
Two or more functions can have the same name but different parameters; such functions are
called function overloading.
#include <iostream>
class Addition
public:
return a+b;
45
return a+b+c;
};
int main(void)
Addition obj;
cout<<obj.sum(20, 15)<<endl;
return 0;
C++ has many functions that allows you to perform mathematical tasks on numbers.
Example
cout << max(5, 10);
Example
cout << min(5, 10);
46
Example
// Include the cmath library
#include <cmath>
cout << sqrt(64);
cout << round(2.6);
cout << log(2);
A list of other popular Math functions (from the <cmath> library) can be found in the table
below:
Function Description
47
fmin(x, y) Returns the lowest value of a floating x and y
Class
Class:It is a user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when
it is instantiated (i.e. an object is created) memory is allocated.
A class is defined in C++ using keyword class followed by the name of class. The body of
class is defined inside the curly brackets and terminated by a semicolon at the end.
48
Declaring Objects: When a class is defined, only the specification for the object is defined; no
memory or storage is allocated. To use the data and access functions defined in the class, you
need to create objects.
Syntax:
ClassName ObjectName;
Accessing data members and member functions: The data members and member functions of
class can be accessed using the dot(.) operator with the object.
For example if the name of object is obj and you want to access the member function with the
name printName() then you will have to write obj.printName() .
Accessing Data Members
The public data members are also accessed in the same way given however the private data
members are not allowed to be accessed directly by the object. Accessing a data member
depends solely on the access control of that data member.
This access control is given by Access modifiers in C++ . There are three access
modifiers : public, private and protected.
#include <iostream>
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
49
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area()
{
return width*height;
}
};
int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
50
Nesting of member functions
A member function can be called by using its name inside another member function of the same
class called Nesting of member function.
A member function can access not only the public functions but also the private functions of the
class it belongs to.
Example:
#include<iostream>
51
const int size=5;
class student
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
};
52
}
void main()
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}
Output:
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343
Like array of other user-defined data types, an array of type class can also be created.
The array of type class contains the objects of the class as its individual elements.
Thus, an array of a class type is also known as an array of objects.
An array of objects is declared in the same way as an array of any built-in data type.
Syntax:
include<iostream>
using namespace std;
class books {
char tit1e [30];
float price ;
public:
void getdata ();
void putdata ();
};
53
void books :: getdata () {
cout<<"Title:;
cin>>title;
cout<<"Price:;
cin>>price;
}
void books :: putdata () {
cout<<"Title:"<<title<< "\n";
cout<<"Price:"<<price<< "\n;
const int size=3 ;
}
int main() {
books book[size] ;
for(int i=0;i<size;i++) {
cout<<"Enter details o£ book "<<(i+1)<<"\n";
book[i].getdata();
}
for(int i=0;i<size;i++) {
cout<<"\nBook "<<(i+l)<<"\n";
book[i].putdata() ;
}
return 0;
}
The output of the program is
Enter details of book 1
Title: c++
Price: 325
Enter details of book 2
Title: DBMS
Price:. 455
Enter details of book 3
Title: Java
Price: 255
Book 1
Title: c++
Price: 325
Book 2
Title: DBMS
54
Price: 455
Book 3
Title: Java
Price: 255
A friend function of a class is a function that is defined outside that class' scope but it has the
right to access all private and protected members of the class.
The friend function is declared using the friend keyword inside the body of the class.
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
The function is not in the scope of the class to which it has been declared a
friend.
It cannot be invoked using the object as it is not in the scope of that class.
It cannot access the member names directly and has to use dot membership
operator and use an object name with the member name.
#include <iostream.h>
55
using namespace std;
class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
void Box::setWidth( double wid ) {
width = wid;
}
int main() {
Box box;
box.setWidth(10.0);
printWidth( box );
return 0;
}
UNIT-IV
Constructors
56
A constructor with no parameters is known as a default constructor.
#include <iostream>
class line
{
public:
void setlength( double len );
double getlength( );
line(); // This is the constructor
private:
double length;
};
return 0;
}
57
When the above code is compiled and executed, it produces the following
result −
Object is being created
Length of line is 6
Parameterized Constructor
Parametrized constructor is a constructor with parameters
where as default constructor does not have any parameter.
It is used to assign initial value to an object at the time of its
creation.
It can have one or more parameters to be initialized to an object at
the time of its creation .
#include <iostream>
private:
double length;
};
return 0;
}
When the above code is compiled and executed, it produces the following
output
Object is being created, length = 10
Length of line : 10
Length of line : 6
Copy constructor
Syntax :
classname (const classname &old_obj);
59
In C++, a Copy Constructor may be called in the following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an
argument.
3. When an object is constructed based on another object of the same class.
4. When the compiler generates a temporary object.
Example :
#include<iostream>
using namespace std;
class point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
point(const Point &p1)
{
x = p1.x; y = p1.y;
}
int getx( )
{
return x;
}
int gety()
{
return y;
}
};
int main()
{
point p1(10, 15); // Normal constructor is called here
// Let us access values assigned by constructors
cout << " p1.x is " << p1.getX() << " p1.y is " << p1.getY();
cout << " \n p2.x is " << p2.getX() << " p2.y is " << p2.getY();
return 0;
60
}
Output:
p1.x is 10 p1.y is 15
p2.x is 10 p2.y is 15
Destructor
A destructor is a special member function of a class that is
executed whenever an object of its class is deleted.
When an object of a class goes out of scope or whenever the delete
expression is applied to a pointer to the object of that class ,
destructor will be invoked.
A destructor will have exact same name as the class prefixed with a
tilde (~).
It does not return a value .
It does not take any parameters.
Destructor can be very useful for releasing resources before coming
out of the program like closing files, releasing memories etc.
Example:
#include <iostream>
using namespace std;
class line
{
public:
void setlength( double len );
61
double getlength( void );
line(); // This is the constructor declaration
~line(); // This is the destructor: declaration
private:
double length;
};
// Member functions definitions including constructor
line::line(void)
{
cout << "Object is being created" << endl;
}
line::~line(void)
{
cout << "Object is being deleted" << endl;
}
void line::setlength( double len )
{
length = len;
}
double line::getlength( void )
{
return length;
}
// Main function for the program
int main()
{
line line;
// set line length
line.setlength(6.0);
cout << "Length of line : " << line.getlength() <<endl;
return 0;
}
62
When the above code is compiled and executed, it produces the
following output
Object is being created
Length of line : 6
Object is being deleted
In C++ , when we create two or more members having the same name with
different number or type of parameters, it is known as function
overloading.
o methods,
o constructors, and
o indexed properties
63
C++ Function Overloading
Function Overloading is defined as the process of having two or more
function with the same name, but different in parameters
The advantage of Function overloading is that it increases the readability of
the program.
Example :
1. #include <iostream>
2. using namespace std;
3. class cal
4. {
5. public:
6. static int add(int a,int b)
7. {
8. return a + b;
9. }
10. static int add(int a, int b, int c)
11. {
12. return a + b + c;
13. }
14. };
64
15. int main(void)
16. {
17. cal obj1; // class object declaration.
18. cout<<obj1.add(10, 20)<<endl;
19. cout<<obj1.add(12, 20, 23);
20. return 0;
21. }
Output:
30
55
66
The following operator can be overloaded :
1. #include <iostream>
2. using namespace std;
3. class test
4. {
5. private:
6. int num;
7. public:
8. test( )
9. {
10. num=8
11. }
12. void operator ++( )
13. {
14. num = num+2;
15. }
16. void print()
17. {
18. cout<<"The Count is: "<<num;
19. }
20. };
21. int main( )
22. {
23. test tt;
24. ++tt; // calling of a function "void operator ++()"
67
25. tt.print();
26. return 0;
27. }
Output:
The Count is: 10
Binary operators take two arguments and following binary operators like
addition (+) operator, subtraction (-) operator and division (/) operator can
be overloaded in c++;
Syntax:
return_type::operator binary_operator_symbol(parameters)
{
// function definition
}
Example :
class complex
{
int a, b;
public:
void get_data()
{
cout << "Enter the value of Complex Numbers a,b:";
cin >> a>>b;
68
}
void display()
{
cout << a << "+" << b << "i" << "\n";
}
};
main()
{
obj1.get_data();
obj2.get_data();
69
Enter the value of Complex Numbers a, b
3 2
Enter the value of Complex Numbers a, b
2 2
Input Values
3 + 2i
2 + 2i
Result
5 + 4i
Type Conversion
C++ allows us to convert data of one type to that of another. This is known
as type conversion.
1. Implicit Conversion
The type conversion that is done automatically done by the compiler is known as
implicit type conversion. This type of conversion is also known as automatic
conversion.
Example :
70
#include <iostream>
using namespace std;
int main() {
// assigning an int value to num_int
int num_int = 9;
// implicit conversion
// assigning int value to a double variable
num_double = num_int;
return 0;
}
Output
num_int = 9
num_double = 9
(data_type)expression;
Eg:
72
Function-style Casting
We can also use the function like notation to cast data from one
type to another.
data_type(expression);
For example,
#include <iostream>
int main() {
73
// initializing a double variable
double num_double = 3.56;
cout << "num_double = " << num_double << endl;
return 0;
}
Output
num_double = 3.56
num_int1 = 3
num_int2 = 3
Unit- IV
74
Constructors and Destructors: Constructors - Parameterized Constructor - Copy constructor
Destructors
Operator Overloading and Type Conversion: Defining operator overloading - Overloading unary
operators Overloading binary operators Rules for operator overloading Type conversion
75