Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Parashar Technologies S P SHARMA CLASSES 9910707562
1 www.spsharmag.com www.parashartechnologies.com
C++ Programming Tutorial
C++ programming is one of the most popular and widely used object -oriented
programming languages which were developed by Bjarne Stroustrup in 1979. C++ is
derived from C programming. So, almost all code that runs on C runs correctly on C++.
C++ is an intermediate level language, as it comprises a confirmation of both high level and low
level language features.
Benefits of C++ over C Language
The major difference being OOPS concept, C++ is an object oriented language whereas C
language is a procedural language. Apart from this there are many other features of C++ which
gives this language an upper hand on C language.
Following features of C++ makes it a stronger language than C,
1. There is Stronger Type Checking in C++.
2. All the OOPS features in C++ like Abstraction, Encapsulation, Inheritance etc makes it more
worthy and useful for programmers.
3. C++ supports and allows user defined operators (i.e. Operator Overloading) and function
overloading is also supported in it.
4. Exception Handling is there in C++.
5. The Concept of Virtual functions and also Constructors and Destructors for Objects.
6. Inline Functions in C++ instead of Macros in C language. Inline functions make complete
function body act like Macro, safely.
7. Variables can be declared anywhere in the program in C++, but must be declared before
they are used.
Object Oriented Programming
Object oriented programming is a programming style that is associated with the concept of
OBJECTS, having data fields and related member functions.
Parashar Technologies S P SHARMA CLASSES 9910707562
2 www.spsharmag.com www.parashartechnologies.com
Objects are instances of classes and are used to interact amongst each other to create
applications. Instance means, the object of class on which we are currently working.
C++ can be said to be as C language with classes. In C++ everything revolves around object of
class, which has their methods & data members.
For Example: We consider human body as a class; we do have multiple objects of this class, with
variable as color, hair etc. and methods as walking, speaking etc.
Now, let us discuss some of the main features of object oriented programming which you will
be using in C++.
1. Objects
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Overloading
7. Exception Handling
Objects
Parashar Technologies S P SHARMA CLASSES 9910707562
3 www.spsharmag.com www.parashartechnologies.com
Objects are the basic unit of OOP. They are instances of class, which have data members and
uses various member functions to perform tasks.
Class
It is similar to structures in C language. Class can also be defined as user defined data type but it
also contains functions in it. So, class is basically a blueprint for object. It declares & defines
what data variables the object will have and what operations can be performed on the class's
object.
Abstraction
Abstraction refers to showing only the essential features of the application and hiding the
details. In C++, classes provide methods to the outside world to access & use the data variables,
but the variables are hidden from direct access.
Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables and
functions together in class.
Inheritance
Inheritance is a way to reuse once written code again and again. The class which is inherited is
called base calls & the class which inherits is called derived class. So when, a derived class
inherits a base class, the derived class can use all the functions which are defined in base class,
hence making code reusable.
Polymorphism
Parashar Technologies S P SHARMA CLASSES 9910707562
4 www.spsharmag.com www.parashartechnologies.com
Polymorphism makes the code more readable. It is a feature, which lets is create functions with
same name but different arguments, which will perform differently. That is function with same
name, functioning in different
Overloading
Overloading is a part of Polymorphism. Where a function or operator is made & defined many
times, to perform different functions they are said to be overloaded.
Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at
runtime.
Syntax and Structure of C++ program
Here we will discuss one simple and basic C++ program to print "Hello this is C++" and its
structure in parts with details and uses.
First C++ program
include <iostream>
using namespace std;
int main()
{
cout << "Hello this is C++";
}
Header files are included at the beginning just like in C program. Here iostream is a header file
which provides us with input & output streams. Header files contained pre-declared function
libraries, which can be used by users for their ease.
Using namespace std, tells the compiler to use standard namespace. Namespace collects
identifiers used for class, object and variables. NameSpace can be used by two ways in a
Parashar Technologies S P SHARMA CLASSES 9910707562
5 www.spsharmag.com www.parashartechnologies.com
program, either by the use of using statement at the beginning, like we did in above mentioned
program or by using name of namespace as prefix before the identifier with scope resolution
(::) operator.
Example : std::cout << "A";
main(), is the function which holds the executing part of program its return type is int .
cout <<, is used to print anything on screen, same as printf in C language. cin and cout are
same as scanf and printf , only difference is that you do not need to mention format specifiers
like, %d for int etc, in cout & cin.
Comments
For single line comments, use // before mentioning comment, like
cout<<"single line"; // This is single line comment
For multiple line comment, enclose the comment between /* and */
/*this is
a multiple line
comment */
Using Classes
Classes name must start with capital letter, and they contain data variables and member
functions. This is a mere introduction to classes; we will discuss classes in detail throughout the
C++ tutorial.
class Abc
{
int i; //data variable
void display() //Member Function
{
cout<<"Inside Member Function";
}
}; // Class ends here
Parashar Technologies S P SHARMA CLASSES 9910707562
6 www.spsharmag.com www.parashartechnologies.com
int main()
{
Abc obj; // Creatig Abc class's object
obj.display(); //Calling member function using class object
}
This is how class is defined, its object is created and the member functions are used.
Variables can be declared anywhere in the entire program, but must be declared, before they
are used.
Data Types in C++
They are used to define type of variables and contents used. Data types define the way you use
storage in the programs you write. Data types can be built in or abstract.
Built in Data Types
These are the data types which are predefined and are wired directly into the compiler. eg: int,
char etc.
User defined or Abstract data types
These are the type, that user creates as a class. In C++ these are classes where as in C it was
implemented by structures.
Basic Built in types
char for character storage ( 1 byte )
int for integral number ( 2 bytes )
float single precision floating point ( 4 bytes )
Parashar Technologies S P SHARMA CLASSES 9910707562
7 www.spsharmag.com www.parashartechnologies.com
double double precision floating point numbers ( 8 bytes )
Example :
char a = 'A'; // character type
int a = 1; // integer type
float a = 3.14159; // floating point type
double a = 6e-4; // double type (e is for exponential)
Other Built in types
bool Boolean ( True or False )
void Without any Value
wchar_t Wide Character
Enum as Data type
Enumerated type declares a new type-name and a sequence of value containing identifiers
which has values starting from 0 and incrementing by 1 every time.
For Example :
enum day(mon, tues, wed, thurs, fri) d;
Here an enumeration of days is defined with variable d. mon will hold value 0, tue will have 1
and so on. We can also explicitly assign values, like, enum day(mon, tue=7, wed); .
Here, mon will be 0, tue is assigned 7, so wed will have value 8.
Modifiers
Parashar Technologies S P SHARMA CLASSES 9910707562
8 www.spsharmag.com www.parashartechnologies.com
Specifiers modify the meanings of the predefined built-in data types and expand them to a
much larger set. There are four data type modifiers in C++, they are:
1. long
2. short
3. signed
4. unsigned
Below mentioned are some important points you must know about the modifiers,
long and short modify the maximum and minimum values that a data type will hold.
A plain int must have a minimum size of short.
Size hierarchy : short int < int < long int
Size hierarchy for floating point numbers is : float < double < long double
long float is not a legal type and there are no short floating point numbers.
Signed types includes both positive and negative numbers and is the default type.
Unsigned, numbers are always without any sign, that is always positive.
What are Variables
Variable are used in C++, where we need storage for any value, which will change in program.
Variable can be declared in multiple ways each with different memory requirements and
functioning. Variable is the name of memory location allocated by the compiler depending
upon the datatype of the variable.
Parashar Technologies S P SHARMA CLASSES 9910707562
9 www.spsharmag.com www.parashartechnologies.com
Basic types of Variables
Each variable while declaration must be given a datatype, on which the memory assigned to the
variable depends. Following are the basic types of variables,
bool For variable to store boolean values( True or False )
char For variables to store character types.
int for variable with integral values
float and double are also types for variables with large and floating point values
Declaration and Initialization
Variable must be declared before they are used. Usually it is preferred to declare them at the
starting of the program, but in C++ they can be declared in the middle of program too, but must
be done before using them.
Parashar Technologies S P SHARMA CLASSES 9910707562
10 www.spsharmag.com www.parashartechnologies.com
Example :
int i; // declared but not initialised
char c;
int i, j, k; // Multiple declaration
Initialization means assigning value to an already declared variable,
int i; // declaration
i = 10; // initialization
Initialization and declaration can be done in one single step also,
int i=10; //initialization and declaration in same step
int i=10, j=11;
If a variable is declared and not initialized by default it will hold a garbage value. Also, if a
variable is once declared and if try to declare it again, we will get a compile time error.
int i,j;
i=10;
j=20;
int j=i+j; //compile time error, cannot redeclare a variable in same scope
Scope of Variables
All the variables have their area of functioning, and out of that boundary they don't hold their
value, this boundary is called scope of the variable. For most of the cases its between the curly
braces, in which variable is declared that a variable exists, not outside it. We will study the
storage classes later, but as of now, we can broadly divide variables into two main types,
Global Variables
Local variables
Global variables
Parashar Technologies S P SHARMA CLASSES 9910707562
11 www.spsharmag.com www.parashartechnologies.com
Global variables are those, which are once declared and can be used throughout the lifetime of
the program by any class or any function. They must be declared outside the main() function.
If only declared, they can be assigned different values at different time in program lifetime. But
even if they are declared and initialized at the same time outside the main() function, then also
they can be assigned any value at any point in the program.
Example : Only declared, not initialized
include <iostream>
using namespace std;
int x; // Global variable declared
int main()
{
x=10; // Initialized once
cout <<"first value of x = "<< x;
x=20; // Initialized again
cout <<"Initialized again with value = "<< x;
}
Local Variables
Local variables are the variables which exist only between the curly braces, in which its
declared. Outside that they are unavailable and leads to compile time error.
Example :
include <iostream>
using namespace std;
int main()
{
int i=10;
if(i<20) // if condition scope starts
{
int n=100; // Local variable declared and initialized
} // if condition scope ends
Parashar Technologies S P SHARMA CLASSES 9910707562
12 www.spsharmag.com www.parashartechnologies.com
cout << n; // Compile time error, n not available here
}
Some special types of variable
There are also some special keywords, to impart unique characteristics to the variables in the
program. Following two are mostly used; we will discuss them in details later.
1. Final - Once initialized, its value can’t be changed.
2. Static - These variables holds their value between function calls.
Example :
include <iostream>
using namespace std;
int main()
{
final int i=10;
static int y=20;
}
Operators in C++
Operators are special type of functions, which takes one or more arguments and produces a new value. For
example: addition (+), substraction (-), multiplication (*) etc, are all operators. Operators are used to perform
various operations on variables and constants.
Parashar Technologies S P SHARMA CLASSES 9910707562
13 www.spsharmag.com www.parashartechnologies.com
Types of operators
1. Assignment Operator
2. Mathematical Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Shift Operators
7. Unary Operators
8. Ternary Operator
9. Comma Operator
Assignment Operator ( = )
Operates '=' is used for assignment, it takes the right-hand side (called rvalue) and copy it into the left-hand
side (called lvalue). Assignment operator is the only operator which can be overloaded but cannot be
inherited.
Mathematical Operators
There are operators used to perform basic mathematical operations. Addition (+), subtraction (-), diversion
(/) multiplication (*) and modulus (%) are the basic mathematical operators. Modulus operator cannot be
used with floating-point numbers.
C++ and C also use a shorthand notation to perform an operation and assignment at same type. Example,
Parashar Technologies S P SHARMA CLASSES 9910707562
14 www.spsharmag.com www.parashartechnologies.com
int x=10;
x += 4 // will add 4 to 10, and hence assign 14 to X.
x -= 5 // will subtract 5 from 10 and assign 5 to x.
Relational Operators
These operators establish a relationship between operands. The relational operators are: less than (<), grater
thatn (>), less than or equal to (<=), greater than equal to (>=), equivalent (==) and not equivalent (! =).
You must notice that assignment operator is (=) and there is a relational operator, for equivalent (==). These
two are different from each other; the assignment operator assigns the value to any variable, whereas
equivalent operator is used to compare values, like in if-else conditions, Example
int x = 10; //assignment operator
x=5; // again assignment operator
if(x == 5) // here we have used equivalent relational operator, for comparison
{
cout <<"Successfully compared";
}
Logical Operators
The logical operators are AND (&&) and OR (||). They are used to combine two different expressions
together.
If two statement are connected using AND operator, the validity of both statements will be considered, but if
they are connected using OR operator, then either one of them must be valid. These operators are mostly
used in loops (especially while loop) and in Decision making.
Bitwise Operators
There are used to change individual bits into a number. They work with only integral data types
like char , int and long and not with floating point values.
Bitwise AND operators &
Bitwise OR operator |
Parashar Technologies S P SHARMA CLASSES 9910707562
15 www.spsharmag.com www.parashartechnologies.com
And bitwise XOR operator ^
And, bitwise NOT operator ~
They can be used as shorthand notation too, & = , |= , ^= , ~= etc.
Shift Operators
Shift Operators are used to shift Bits of any variable. It is of three types,
1. Left Shift Operator <<
2. Right Shift Operator >>
3. Unsigned Right Shift Operator >>>
Unary Operators
These are the operators which work on only one operand. There are many unary operators, but
increment ++ and decrement -- operators are most used.
Other Unary Operators: address of & , dereference * , new and delete, bitwise not ~ , logical not ! , unary
minus - and unary plus + .
Ternary Operator
The ternary if-else ? : is an operator which has three operands.
int a = 10;
a > 5 ? cout << "true" : cout << "false"
Comma Operator
This is used to separate variable names and to separate expressions. In case of expressions, the value of last
expression is produced and used.
Example :
int a,b,c; // variables declaration using comma operator
a=b++, c++; // a = c++ will be done.
Parashar Technologies S P SHARMA CLASSES 9910707562
16 www.spsharmag.com www.parashartechnologies.com
sizeof operator in C++
sizeOf is also an operator not a function, it is used to get information about the amount of memory allocated
for data types & Objects. It can be used to get size of user defined data types too.
sizeOf operator can be used with and without parentheses. If you apply it to a variable you can use it without
parentheses.
cout << sizeOf(double); //Will print size of double
int x = 2;
int i = sizeOf x;
typedef Operator
typedef is a keyword used in C language to assign alternative names to existing types. It’s mostly used with
user defined data types, when names of data types get slightly complicated. Following is the general syntax
for using typedef,
typedef existing_name alias_name
Lets take an example and see how typedef actually works.
typedef unsigned long ulong;
The above statement defines a term ulong for an unsigned long type. Now this ulong identifier can be used
to define unsigned long type variables.
ulong i, j ;
typedef and Pointers
typedef can be used to give an alias name to pointers also. Here we have a case in which use of typedef is
beneficial during pointer declaration.
In Pointers * binds to the right and not the left.
int* x, y ;
By this declaration statement, we are actually declaring x as a pointer of type int, whereas y will be declared
as a plain integer.
typedef int* IntPtr ;
Parashar Technologies S P SHARMA CLASSES 9910707562
17 www.spsharmag.com www.parashartechnologies.com
IntPtr x, y, z;
But if we use typedef like in above example, we can declare any number of pointers in a single statement.
Decision making in C++
Decision making is about deciding the order of execution of statements based on certain conditions or repeat
a group of statements until certain specified conditions are met. C++ handles decision-making by supporting
the following statements,
if statement
switch statement
conditional operator statement
goto statement
Decision making with if statement
The if statement may be implemented in different forms depending on the complexity of conditions to be
tested. The different forms are,
1. Simple if statement
2. If....else statement
3. Nested if....else statement
4. else if statement
Simple if statement
The general form of a simple if statement is,
if( expression )
{
statement-inside;
}
statement-outside;
Parashar Technologies S P SHARMA CLASSES 9910707562
18 www.spsharmag.com www.parashartechnologies.com
If the expression is true, then 'statement-inside' it will be executed, otherwise 'statement-inside' is skipped
and only 'statement-outside' is executed.
Example :
#include< iostream.h>
int main( )
{
int x,y;
x=15;
y=13;
if (x > y )
{
cout << "x is greater than y";
}
}
Output : x is greater than y
if...else statement
The general form of a simple if...else statement is,
if( expression )
{
statement-block1;
}
else
{
statement-block2;
}
If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1' is skipped and
'statement-block2' is executed.
Parashar Technologies S P SHARMA CLASSES 9910707562
19 www.spsharmag.com www.parashartechnologies.com
Example :
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
cout << "x is greater than y";
}
else
{
cout << "y is greater than x";
}
}
Output : y is greater than x
Nested if....else statement
The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
Parashar Technologies S P SHARMA CLASSES 9910707562
20 www.spsharmag.com www.parashartechnologies.com
statement-block 2;
}
}
else
{
statement-block 3;
}
if 'expression' is false the 'statement-block3' will be executed, otherwise it continues to perform the test for
'expression 1' . If the 'expression 1' is true the 'statement-block1' is executed otherwise 'statement-block2' is
executed.
Example :
void main( )
{
int a,b,c;
clrscr();
cout << "enter 3 number";
cin >> a >> b >> c;
if(a > b)
{
if( a > c)
{
cout << "a is greatest";
}
else
{
cout << "c is greatest";
}
}
else
Parashar Technologies S P SHARMA CLASSES 9910707562
21 www.spsharmag.com www.parashartechnologies.com
{
if( b> c)
{
cout << "b is greatest";
}
else
{
printf("c is greatest");
}
}
getch();
}
else-if ladder
The general form of else-if ladder is,
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
Parashar Technologies S P SHARMA CLASSES 9910707562
22 www.spsharmag.com www.parashartechnologies.com
default-statement;
The expression is tested from the top(of the ladder) downwards. As soon as the true condition is found, the
statement associated with it is executed.
Example :
void main( )
{
int a;
cout << "enter a number";
cin >> a;
if( a%5==0 && a%8==0)
{
cout << "divisible by both 5 and 8";
}
else if( a%8==0 )
{
cout << "divisible by 8";
}
else if(a%5==0)
{
cout << "divisible by 5";
}
else
{
cout << "divisible by none";
}
getch();
}
Points to Remember
Parashar Technologies S P SHARMA CLASSES 9910707562
23 www.spsharmag.com www.parashartechnologies.com
1. In if statement, a single statement can be included without enclosing it into curly braces { }
int a = 5;
if(a > 4)
cout << "success";
No curly braces are required in the above case, but if we have more than one statement
inside if condition, then we must enclose them inside curly braces.
2. == must be used for comparison in the expression of if condition, if you use = the expression will
always return true, because it performs assignment not comparison.
3. Other than 0(zero), all other values are considered as true.
if(27)
cout << "hello";
In above example, hello will be printed.
Looping in C++
In any programming language, loops are used to execute a set of statements repeatedly until a particular
condition is satisfied.
How it works
Parashar Technologies S P SHARMA CLASSES 9910707562
24 www.spsharmag.com www.parashartechnologies.com
A sequence of statement is executed until a specified condition is true. This sequence of statement to be
executed is kept inside the curly braces { } known as loop body. After every execution of loop body,
condition is checked, and if it is found to be true the loop body is executed again. When condition check
comes out to be false, the loop body will not be executed.
There are 3 type of loops in C++ language
1. while loop
2. for loop
3. do-while loop
while loop
while loop can be address as an entry control loop. It is completed in 3 steps.
Variable initialization.( e.g int x=0; )
condition( e.g while( x<=10) )
Parashar Technologies S P SHARMA CLASSES 9910707562
25 www.spsharmag.com www.parashartechnologies.com
Variable increment or decrement ( x++ or x-- or x=x+2 )
Syntax :
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}
for loop
for loop is used to execute a set of statement repeatedly until a particular condition is satisfied. We can say it
an open ended loop. General format is,
for(initialization; condition ; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after condition. In this loop we
can have more than one initialization or increment/decrement, separated using comma operator. for loop
can have only one condition.
Nested for loop
We can also have nested for loop, i.e one for loop inside another for loop. Basic syntax is,
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
Parashar Technologies S P SHARMA CLASSES 9910707562
26 www.spsharmag.com www.parashartechnologies.com
}
}
do while loop
In some situations it is necessary to execute body of the loop before testing the condition. Such situations
can be handled with the help of do-while loop. do statement evaluates the body of the loop first and at the
end, the condition is checked using while statement. General format of do-while loop is,
do
{
....
.....
}
while(condition)
Jumping out of loop
Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as
soon as certain condition becomes true, that is jump out of loop. C language allows jumping from one
statement to another within a loop as well as jumping out of the loop.
1) break statement
When break statement is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop.
2) continue statement
It causes the control to go directly to the test-condition and then continue the loop process. On encountering
continue, cursor leave the current cycle of loop, and starts with the next cycle.
Storage Classes in C++
Storage classes are used to specify the lifetime and scope of variables. How storage is allocated for variables
and how variable is treated by complier depends on these storage classes.
Parashar Technologies S P SHARMA CLASSES 9910707562
27 www.spsharmag.com www.parashartechnologies.com
These are basically divided into 5 different types:
1. Global variables
2. Local variables
3. Register variables
4. Static variables
5. Extern variables
Global Variables
These are defined at the starting, before all function bodies and are available throughout the program.
using namespace std;
int globe; // Global variable
void func();
int main()
{
.....
}
Local variables
They are defined and are available within a particular scope. They are also called Automatic variable because
they come into being when scope is entered and automatically go away when the scope ends.
The keyword auto is used, but by default all local variables are auto, so we don't have to explicitly add
keyword auto before variable declaration. Default value of such variable is garbage.
Register variables
This is also a type of local variable. This keyword is used to tell the compiler to make access to this variable as
fast as possible. Variables are stored in registers to increase the access speed.
But you can never use or compute address of register variable and also, a register variable can be declared
only within a block that means, you cannot have global or static register variables.
Parashar Technologies S P SHARMA CLASSES 9910707562
28 www.spsharmag.com www.parashartechnologies.com
Static Variables
Static variables are the variables which are initialized & allocated storage only once at the beginning of
program execution, no matter how many times they are used and called in the program. A static variable
retains its value until the end of program.
void fun()
{
static int i = 10;
i++;
cout << i;
}
int main()
{
fun(); // Output = 11
fun(); // Output = 12
fun(); // Output = 13
}
As, i is static, hence it will retain its value through function calls, and is initialized only once at the beginning.
Static specifiers are also used in classes, but that we will learn later.
Extern Variables
This keyword is used to access variable in a file which is declared & defined in some other file, that is the
existence of a global variable in one file is declared using extern keyword in another file.
Parashar Technologies S P SHARMA CLASSES 9910707562
29 www.spsharmag.com www.parashartechnologies.com
Functions in C++
Functions are used to provide modularity to a program. Creating an application using function makes it easier
to understand, edit, check errors etc.
Syntax of Function
return-type function-name (parameters)
{
// function-body
}
return-type: suggests what the function will return. It can be int, char, some pointer or even a class
object. There can be a function which does not return anything, they are mentioned with void.
Function Name: is the name of the function, using the function name it is called.
Parameters: are variables to hold values of arguments passed while function is called. A function may or
may not contain parameter list.
Parashar Technologies S P SHARMA CLASSES 9910707562
30 www.spsharmag.com www.parashartechnologies.com
void sum(int x, int y)
{
int z;
z = x + y;
cout << z;
}
int main()
{
int a = 10;
int b = 20;
sum (a, b);
}
Here, a and b are sent as arguments, and x and y are parameters which will hold values of a and b to
perform required operation inside function.
Function body: is he part where the code statements are written.
Declaring, Defining and Calling Function
Function declaration, is done to tell the compiler about the existence of the function. Function's return type,
its name & parameter list is mentioned. Function body is written in its definition. Let’s understand this with
help of an example.
#include <iostream>
using namespace std;
int sum (int x, int y); //declaring function
int main()
{
int a = 10;
Parashar Technologies S P SHARMA CLASSES 9910707562
31 www.spsharmag.com www.parashartechnologies.com
int b = 20;
int c = sum (a, b); //calling function
cout << c;
}
int sum (int x, int y) //defining function
{
return (X + y);
}
Here, initially the function is declared, without body. Then inside main() function it is called, as the function
returns summation of two values, hence z is store the value of sum. Then, at last, function is defined, where
the body of function is mentioned. We can also, declare & define the function together, but then it should be
done before it is called.
Calling a Function
Functions are called by their names. If the function is without argument, it can be called directly using its
name. But for functions with arguments, we have two ways to call them,
1. Call by Value
2. Call by Reference
Call by Value
In this calling technique we pass the values of arguments which are stored or copied into the formal
parameters of functions. Hence, the original values are unchanged only the parameters inside function
changes.
void calc(int x);
int main()
{
int x = 10;
Parashar Technologies S P SHARMA CLASSES 9910707562
32 www.spsharmag.com www.parashartechnologies.com
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
}
Output : 10
In this case the actual variable x is not changed, because we pass argument by value, hence a copy of x is
passed, which is changed, and that copied value is destroyed as the function ends (goes out of scope). So the
variable x inside main() still has a value 10.
But we can change this program to modify the original x, by making the function calc() return a value, and
storing that value in x.
int calc(int x);
int main()
{
int x = 10;
x = calc(x);
printf("%d", x);
}
int calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20
Parashar Technologies S P SHARMA CLASSES 9910707562
33 www.spsharmag.com www.parashartechnologies.com
Call by Reference
In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a
reference or a pointer; in both the case they will change the values of the original variable.
void calc(int *p);
int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}
void calc(int *p)
{
*p = *p + 10;
}
Output : 20
Introduction to Classes and Objects
The classes are the most important feature of C++ that leads to Object Oriented programming. Class is a user
defined data type, which holds its own data members and member functions, which can be accessed and
used by creating instance of that class.
The variables inside class definition are called as data members and the functions are called member
functions.
For example: Class of birds, all birds can fly and they all have wings and beaks. So here flying is a behavior
and wings and beaks are part of their characteristics. And there are many different birds in this class with
different names but them all posses this behavior and characteristics.
Similarly, class is just a blue print, which declares and defines characteristics and behavior, namely data
members and member functions respectively. And all objects of this class will share these characteristics and
behavior.
Parashar Technologies S P SHARMA CLASSES 9910707562
34 www.spsharmag.com www.parashartechnologies.com
More about Classes
1. Class name must start with an uppercase letter. If class name is made of more than one word, then first
letter of each word must be in uppercase. Example,
class Study, class Ptech etc
2. Classes contain data members and member functions, and the access of these data members and
variable depends on the access specifies (discussed in next section).
3. Class's member functions can be defined inside the class definition or outside the class definition.
4. Class in C++ is similar to structures in C, the only difference being, class defaults to private access control,
where as structure defaults to public.
5. All the features of OOPS, revolve around classes in C++. Inheritance, Encapsulation, Abstraction etc.
6. Objects of class holds separate copies of data members. We can create as many objects of a class as we
need.
7. Classes do posses more characteristics, like we can create abstract classes, immutable classes, all this we
will study later.
Objects
Class is mere a blueprint or a template. No storage is assigned when we define a class. Objects are instances
of class, which holds the data variables declared in class and the member functions work on these class
objects.
Each object has different data variables. Objects are initialized using special class functions called.
And whenever the object is out of its scope, another special class member function called Destructor is
called, to release the memory reserved by the object. C++ doesn't have Automatic Garbage Collector like in
JAVA, in C++ Destructor performs this task.
class Abc
{
Parashar Technologies S P SHARMA CLASSES 9910707562
35 www.spsharmag.com www.parashartechnologies.com
int x;
void display(){} //empty function
};
in main()
{
Abc obj; // Object of class Abc created
}
Access Control in Classes
Now before studying how to define class and its objects, lets first quickly learn what are access specifiers.
Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords introduced, namely,
1. public
2. private
3. protected
These access specifiers are used to set boundaries for availability of members of class be it data members or
member functions
Access specifiers in the program, are followed by a colon. You can use either one, two or all 3 specifiers in the
same class to set different boundaries for different class members. They change the boundary for all the
declarations that follow them.
Public
Public, means all the class members declared under public will be available to everyone. The data members
and member functions declared public can be accessed by other classes too. Hence there are chances that
they might change them. So the key members must not be declared public.
class PublicAccess
{
public: // public access specifier
Parashar Technologies S P SHARMA CLASSES 9910707562
36 www.spsharmag.com www.parashartechnologies.com
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Private
Private keyword means that no one can access the class members declared private outside that class. If
someone tries to access the private member, they will get a compile time error. By default class variables and
member functions are private.
class PrivateAccess
{
private: // private access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Protected
Protected, is the last access specifier, and it is similar to private, it makes class member inaccessible outside
the class. But they can be accessed by any subclass of that class. (If class A is inherited by class B, then class B
is subclass of class A. We will learn this later.)
class ProtectedAccess
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Defining Class and Declaring Objects
Parashar Technologies S P SHARMA CLASSES 9910707562
37 www.spsharmag.com www.parashartechnologies.com
When we define any class, we are not defining any data; we just define a structure or a blueprint, as to what
the object of that class type will contain and what operations can be performed on that object.
Below is the syntax of class definition,
class ClassName
{
Access specifier:
Data members;
Member Functions(){}
};
Here is an example; we have made a simple class named Student with appropriate members,
class Student
{
public:
int rollno;
string name;
};
So its clear from the syntax and example, class definition starts with the keyword "class" followed by the class
name. Then inside the curly braces comes the class body that is data members and member functions, whose
access is bounded by access specifier. A class definition ends with a semicolon, or with a list of object
declarations.
Example :
class Student
{
public:
int rollno;
Parashar Technologies S P SHARMA CLASSES 9910707562
38 www.spsharmag.com www.parashartechnologies.com
string name;
}A,B;
Here A and B are the objects of class Student, declared with the class definition. We can also declare objects
separately, like we declare variable of primitive data types. In this case the data type is the class name, and
variable is the object.
int main()
{
Student A;
Student B;
}
Both A and B will have their own copies of data members.
Accessing Data Members of Class
Accessing a data member depends solely on the access control of that data member. If it’s public, then the
data member can be easily accessed using the direct member access (.) operator with the object of that
class.
If, the data member is defined as private or protected, then we cannot access the data variables directly.
Then we will have to create special public member functions to access, use or initialize the private and
protected data members. These member functions are also called Accessors and Mutator methods
or getter and setter functions.
Accessing Public Data Members
Following is an example to show you how to initialize and use the public data members using the dot (.)
operator and the respective object of class.
class Student
{
public:
Parashar Technologies S P SHARMA CLASSES 9910707562
39 www.spsharmag.com www.parashartechnologies.com
int rollno;
string name;
};
int main()
{
Student A;
Student B;
A.rollno=1;
A.name="Adam";
B.rollno=2;
B.name="Bella";
cout <<"Name and Roll no of A is :"<< A.name << A.rollno;
cout <<"Name and Roll no of B is :"<< B.name << B.rollno;
}
Accessing Private Data Members
To access, use and initialize the private data member you need to create getter and setter functions, to get
and set the value of the data member.
The setter function will set the value passed as argument to the private data member, and the getter
function will return the value of the private data member to be used. Both getter and setter function must be
defined public.
Example:
class Student
{
private: // private data member
Parashar Technologies S P SHARMA CLASSES 9910707562
40 www.spsharmag.com www.parashartechnologies.com
int rollno;
public: // public accessor and mutator functions
int getRollno()
{
return rollno;
}
void setRollno(int i)
{
rollno=i;
}
};
int main()
{
Student A;
A.rollono=1; //Compile time error
cout<< A.rollno; //Compile time error
A.setRollno(1); //Rollno initialized to 1
cout<< A.getRollno(); //Output will be 1
}
So this is how we access and use the private data members of any class using the getter and setter methods.
We will discuss this in more details later.
Parashar Technologies S P SHARMA CLASSES 9910707562
41 www.spsharmag.com www.parashartechnologies.com
Accessing Protected Data Members
Protected data members, can be accessed directly using dot (.) operator inside the subclass of the current
class, for non-subclass we will have to follow the steps same as to access private data member.
Member Functions in Classes Member functions are the functions, which have their declaration inside the class definition and works on the data members of the class. The definition of member functions can be inside or outside the definition of class.
If the member function is defined inside the class definition it can be defined directly, but if its
defined outside the class, then we have to use the scope resolution :: operator along with class
name along with function name.
Example:
class Cube
{
public:
int side;
int getVolume(); // Declaring function getVolume with no argument and return type int.
};
If we define the function inside class then we don't not need to declare it first, we can directly define the function.
class Cube
{
public:
int side;
int getVolume()
{
return side*side*side; //returns volume of cube
}
};
Parashar Technologies S P SHARMA CLASSES 9910707562
42 www.spsharmag.com www.parashartechnologies.com
But if we plan to define the member function outside the class definition then we must declare the function inside class definition and then define it outside.
class Cube
{
public:
int side;
int getVolume();
}
int Cube :: getVolume() // defined outside class definition
{
return side*side*side;
}
The main() function for both the function definition will be same. Inside main() we will create
object of class, and will call the member function using dot . operator.
int main()
{
Cube C1;
C1.side=4; // setting side value
cout<< "Volume of cube C1 ="<< C1.getVolume();
}
Similarly we can define the getter and setter functions to access private data members, inside or outside the class definition.
Types of Member Functions
We already know what member functions are and what they do. Now lets study some special member
functions present in the class. Following are different types of Member functions,
Parashar Technologies S P SHARMA CLASSES 9910707562
43 www.spsharmag.com www.parashartechnologies.com
1. Simple functions
2. Static functions
3. Const functions
4. Inline functions
5. Friend functions
Simple Member functions
These are the basic member function, which don’t have any special keyword like static etc as prefix. All the
general member functions, which are of below given form, are termed as simple and basic member
functions.
return_type functionName(parameter_list)
{
function body;
}
Static Member functions
Static is something that holds its position. Static is a keyword which can be used with data members as well
as the member functions. We will discuss this in details later. As of now we will discuss its usage with
member functions only.
A function is made static by using static keyword with function name. These functions work for the class as
whole rather than for a particular object of a class.
It can be called using the object and the direct member access . operator. But, its more typical to call a static
member function by itself, using class name and scope resolution :: operator.
Example :
class X
{
public:
Parashar Technologies S P SHARMA CLASSES 9910707562
44 www.spsharmag.com www.parashartechnologies.com
static void f(){};
};
int main()
{
X::f(); // calling member function directly with class name
}
These functions cannot access ordinary data members and member functions, but only static data members
and static member functions.
It doesn't have any "this" keyword which is the reason it cannot access ordinary members. We will study
about "this" keyword later.
Const Member functions
We will study Const keyword in detail later, but as an introduction, Const keyword makes variables constant,
that means once defined, there values can't be changed.
When used with member function, such member functions can never modify the object or its related data
members.
//Basic Syntax of const Member Function
void fun() const {}
Inline functions
All the member functions defined inside the class definition are by default declared as Inline. We will study
Inline Functions in details in the next topic.
Friend functions
Parashar Technologies S P SHARMA CLASSES 9910707562
45 www.spsharmag.com www.parashartechnologies.com
Friend functions are actually not class member function. Friend functions are made to give private access to
non-class functions. You can declare a global function as friend, or a member function of other class as friend.
Example:
class WithFriend
{
int i;
public:
friend void fun(); // Global function as friend
};
void fun()
{
WithFriend wf;
wf.i=10; // Access to private data member
cout << wf.i;
}
int main()
{
fun(); //Can be called directly
}
Hence, friend functions can access private data members by creating object of the class. Similarly we can also
make function of other class as friend, or we can also make an entire class as friend class.
class Other
{
void fun();
};
class WithFriend
{
Parashar Technologies S P SHARMA CLASSES 9910707562
46 www.spsharmag.com www.parashartechnologies.com
private:
int i;
public:
void getdata(); // Member function of class WithFriend
friend void Other::fun(); // making function of class Other as friend here
friend class Other; // making the complete class as friend
};
When we make a class as friend, all its member functions automatically become friend functions.
Friend Functions is a reason, why C++ is not called as a pure Object Oriented language. Because it violates the
concept of Encapsulation.
Inline Functions in C++
All the member functions defined inside the class definition are by default declared as Inline. Let us have
some background knowledge about these functions.
You must remember Preprocessors from C language. Inline functions in C++ do the same thing what Macros
do in C. Preprocessors were not used in C++ because they had some drawbacks.
Drawbacks of Macro
In Macro, we define certain variable with its value at the beginning of the program, and everywhere inside
the program where we use that variable; it’s replaced by its value on Compilation.
1) Problem with spacing
Let us see this problem using an example,
#define G (y) (y+1)
Here we have defined a Macro with name G(y), which is to be replaced by its value that is (y + 1) during
compilation. But, what actually happens when we call G(y),
G(1) //Macro will replace it
the preprocessor will expand it like,
(y) (y+1) (1)
Parashar Technologies S P SHARMA CLASSES 9910707562
47 www.spsharmag.com www.parashartechnologies.com
You must be thinking why this happened, this happened because of the spacing in Macro definition. Hence
big functions with several expressions can never be used with macro, so Inline functions were introduced in
C++.
2) Complex Argument Problem
In some cases such Macro expressions work fine for certain arguments but when we use complex arguments
problems start arising.
#define MAX(x,y) x>y?1:0
Now if we use the expression,
if(MAX(a&0x0f,0x0f)) // Complex Argument
Macro will Expand to,
if( a&0x0f > 0x0f ? 1:0)
Here precedence of operators will lead to problem, because precedence of & is lower than that of > , so the
macro evaluation will surprise you. This problem can be solved though using parenthesis, but still for bigger
expressions problem will arise.
3) No way to access Private Members of Class
With Macros, in C++ you can never access private variables, so you will have to make those members public,
which will expose the implementation.
class Y
{
int x;
public :
#define VAL(Y::x) // Its an Error
}
Inline Functions
Inline functions are actual functions, which are copied everywhere during compilation, like preprocessor
macro, so the overhead of function calling is reduced. All the functions defined inside class definition are by
default inline, but you can also make any non-class function inline by using keyword inline with them.
Parashar Technologies S P SHARMA CLASSES 9910707562
48 www.spsharmag.com www.parashartechnologies.com
For an inline function, declaration and definition must be done together. For example,
inline void fun(int a)
{
return a++;
}
Some Important points about Inline Functions
1. We must keep inline functions small, small inline functions have better efficiency.
2. Inline functions do increase efficiency, but we should not make all the functions inline. Because if we
make large functions inline, it may lead to code bloat, and might affect the speed too.
3. Hence, it is advice to define large functions outside the class definition using scope
resolution :: operator, because if we define such functions inside class definition, then they become
inline automatically.
4. Inline functions are kept in the Symbol Table by the compiler, and all the call for such functions is taken
care at compile time.
Access Functions
We have already studied this in topic Accessing Private Data variables inside class. We use access functions,
which are inline to do so.
class Auto
{
int i;
public:
int getdata()
{
return i;
}
Parashar Technologies S P SHARMA CLASSES 9910707562
49 www.spsharmag.com www.parashartechnologies.com
void setdata(int x)
{
i=x;
}
};
Here getdata() and setdata() are inline functions, and are made to access the private data members of the
class Auto. getdata(), in this case is called Accessor function and setdata() is a Mutator function.
There can be overlaoded Accessor and Mutator functions too. We will study overloading functions in next
topic.
Limitations of Inline Functions
1. The compiler is unable to perform inlining if the function is too complicated. So we must avoid big
looping conditions inside such functions. In case of inline functions, entire function body is inserted in
place of each call, so if the function is large it will affect speed and memory badly.
2. Also, if we require address of the function in program, compiler cannot perform inlining on such
functions. Because for providing address to a function, compiler will have to allocate storage to it. But
inline functions doesn't get storage, they are kept in Symbol table.
Forward References
All the inline functions are evaluated by the compiler, at the end of class declaration.
class ForwardReference
{
int i;
public:
int f() {return g()+10;} // call to undeclared function
int g() {return i;}
Parashar Technologies S P SHARMA CLASSES 9910707562
50 www.spsharmag.com www.parashartechnologies.com
};
int main()
{
ForwardReference fr;
fr.f();
}
You must be thinking that this will lead to compile time error, but in this case it will work, because no inline
function in a class is evaluated until the closing braces of class declaration.
Function Overloading
If any class has multiple functions with same names but different parameters then they are said to be
overloaded. Function overloading allows you to use the same name for different functions, to perform, either
same or different functions in the same class.
Function overloading is usually used to enhance the readability of the program. If you have to perform one
single operation but with different number or types of arguments, then you can simply overload the function.
Ways to overload a function
1. By changing number of Arguments.
2. By having different types of argument.
Number of Arguments different
In this type of function overloading we define two functions with same names but different number of
parameters of the same type. For example, in the below mentioned program we have made two sum()
functions to return sum of two and three integers.
int sum (int x, int y)
{
cout << x+y;
Parashar Technologies S P SHARMA CLASSES 9910707562
51 www.spsharmag.com www.parashartechnologies.com
}
int sum(int x, int y, int z)
{
cout << x+y+z;
}
Here sum() function is overloaded, to have two and three arguments. Which sum() function will be called,
depends on the number of arguments.
int main()
{
sum (10,20); // sum() with 2 parameter will be called
sum(10,20,30); //sum() with 3 parameter will be called
}
Different Datatype of Arguments
In this type of overloading we define two or more functions with same name and same number of
parameters, but the type of parameter is different. For example in this program, we have two sum() function,
first one gets two integer arguments and second one gets two double arguments.
int sum(int x,int y)
{
cout<< x+y;
}
double sum(double x, double y)
{
cout << x+y;
}
Parashar Technologies S P SHARMA CLASSES 9910707562
52 www.spsharmag.com www.parashartechnologies.com
int main()
{
sum (10,20);
sum(10.5,20.5);
}
Default Arguments
When we mention a default value for a parameter while declaring the function, it is said to be as default
argument. In this case, even if we make a call to the function without passing any value for that parameter,
the function will take the default value specified.
sum(int x,int y=0)
{
cout << x+y;
}
Here we have provided a default value for y, during function definition.
int main()
{
sum(10);
sum(10,0);
sum(10,10);
}
Output : 10 10 20 First two function calls will produce the exact same value.
for the third function call, y will take 10 as value and output will become 20.
By setting default argument, we are also overloading the function. Default arguments also allow you to use
the same function in different situations just like function overloading.
Rules for using Default Arguments
Parashar Technologies S P SHARMA CLASSES 9910707562
53 www.spsharmag.com www.parashartechnologies.com
1. Only the last argument must be given default value. You cannot have a default argument followed by
non-default argument.
sum (int x,int y);
sum (int x,int y=0);
sum (int x=0,int y); // This is Incorrect
2. If you default an argument, then you will have to default all the subsequent arguments after that.
sum (int x,int y=0);
sum (int x,int y=0,int z); // This is incorrect
sum (int x,int y=10,int z=10); // Correct
3. You can give any value a default value to argument, compatible with its datatype.
Placeholder Arguments
When arguments in a function are declared without any identifier they are called placeholder arguments.
void sum (int,int);
Such arguments can also be used with default arguments.
void sum (int, int=0);
Constructors
Constructors are special class functions which performs initialization of every object. The Compiler calls the
Constructor whenever an object is created. Constructors initialize values to object members after storage is
allocated to the object.
class A
{
int x;
public:
A(); //Constructor
Parashar Technologies S P SHARMA CLASSES 9910707562
54 www.spsharmag.com www.parashartechnologies.com
};
While defining a constructor you must remember that the name of constructor will be same as the name of
the class, and constructors never have return type.
Constructors can be defined either inside the class definition or outside class definition using class name and
scope resolution :: operator.
class A
{
int i;
public:
A(); //Constructor declared
};
A::A() // Constructor definition
{
i=1;
}
Types of Constructors
Constructors are of three types:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax :
Parashar Technologies S P SHARMA CLASSES 9910707562
55 www.spsharmag.com www.parashartechnologies.com
class_name ()
{ Constructor Definition }
Example :
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};
int main()
{
Cube c;
cout << c.side;
}
Output : 10
In this case, as soon as the object is created the constructor is called which initializes its data members.
A default constructor is so important for initialization of object members, that even if we do not define a
constructor explicitly, the compiler will provide a default constructor implicitly.
class Cube
{
int side;
};
int main()
{
Parashar Technologies S P SHARMA CLASSES 9910707562
56 www.spsharmag.com www.parashartechnologies.com
Cube c;
cout << c.side;
}
Output : 0
In this case, default constructor provided by the compiler will be called which will initialize the object data
members to default value that will be 0 in this case.
Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide different values to data
members of different objects, by passing the appropriate values as argument.
Example:
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
Parashar Technologies S P SHARMA CLASSES 9910707562
57 www.spsharmag.com www.parashartechnologies.com
cout << c3.side;
}
OUTPUT : 10 20 30
By using parameterized constructor in above case, we have initialized 3 objects with user defined values. We
can have any number of parameters in a constructor.
Copy Constructor
These are special type of Constructors which takes an object as argument, and is used to copy values of data
members of one object into other object. We will study copy constructors in detail later.
Constructor Overloading
Just like other member functions, constructors can also be overloaded. Infact when you have both default
and parameterized constructors defined in your class you are having Overloaded Constructors, one with no
parameter and other with parameter.
You can have any number of Constructors in a class that differ in parameter list.
class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
Parashar Technologies S P SHARMA CLASSES 9910707562
58 www.spsharmag.com www.parashartechnologies.com
{
rollno=x ;
name=str ;
}
};
int main()
{
Student A(10);
Student B(11,"Ram");
}
In above case we have defined two constructors with different parameters, hence overloading the
constructors.
One more important thing, if you define any constructor explicitly, then the compiler will not provide default
constructor and you will have to define it yourself.
In the above case if we write Student S; in main(), it will lead to a compile time error, because we haven't
defined default constructor, and compiler will not provide its default constructor because we have defined
other parameterized constructors.
Destructors
Destructor is a special class function which destroys the object as soon as the scope of object ends. The
destructor is called automatically by the compiler when the object goes out of scope.
The syntax for destructor is same as that for the constructor, the class name is used for the name of
destructor; with a tilde ~ sign as prefix to it.
class A
{
public:
~A();
};
Parashar Technologies S P SHARMA CLASSES 9910707562
59 www.spsharmag.com www.parashartechnologies.com
Destructors will never have any arguments.
Example to see how Constructor and Destructor is called
class A
{
A()
{
cout << "Constructor called";
}
~A()
{
cout << "Destructor called";
}
};
int main()
{
A obj1; // Constructor Called
int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Parashar Technologies S P SHARMA CLASSES 9910707562
60 www.spsharmag.com www.parashartechnologies.com
Single Definition for both Default and Parameterized Constructor
In this example we will use default argument to have a single definition for both default and parameterized
constructor.
class Dual
{
int a;
public:
Dual(int x=0)
{
a=x;
}
};
int main()
{
Dual obj1;
Dual obj2(10);
}
Here, in this program, a single Constructor definition will take care for both these object initializations. We
don't need separate default and parameterized constructors.
Namespace
Namespace is a container for identifiers. It puts the names of its members in a distinct space so that they
don't conflict with the names in other namespaces or global namespace.
Creating a Namespace
Creating a namespace is similar to creation of a class.
namespace MySpace
Parashar Technologies S P SHARMA CLASSES 9910707562
61 www.spsharmag.com www.parashartechnologies.com
{
// Declarations
}
int main() {}
This will create a namespace called MySpace, inside which we can put our member declarations.
Rules to create Namespace
1. The namespace definition must be done at global scope, or nested inside another namespace.
2. Namespace definition doesn't terminate with a semicolon like in class definition.
3. You can use an alias name for your namespace name, for ease of use.
Example for Alias :
namespace PTech
{
void study();
class Learn { };
}
namespace St PTech; // St is now alias for PTech
4. You cannot create instance of namespace.
5. There can be unnamed namespaces too. Unnamed namespace is unique for each translation unit. They
act exactly like named namespaces.
Example for Unnamed namespace:
namespace
{
class Head { };
class Tail { };
Parashar Technologies S P SHARMA CLASSES 9910707562
62 www.spsharmag.com www.parashartechnologies.com
int i,j,k;
}
int main() { }
6. A namespace definition can be continued and extended over multiple files, they are not redefined or
overridden.
Example:
Header1.h
namespace MySpace
{
int x;
void f();
}
Header2.h
#include "Header1.h";
namespace MySpace
{
int y;
void g();
}
Using a Namespace
There are three ways to use a namespace in program,
1. Scope Resolution
2. The using directive
3. The using declaration
Parashar Technologies S P SHARMA CLASSES 9910707562
63 www.spsharmag.com www.parashartechnologies.com
With Scope Resolution
Any name (identifier) declared in a namespace can be explicitly specified using the namespace's name and
the scope resolution :: operator with the identifier.
namespace MySpace
{
class A
{
static int i;
public:
void f();
};
class B; // class name declaration
void func(); //gobal function declaration
}
int MySpace::A::i=9; // Initializing static class variable
class MySpace::B
{
int x;
public:
int getdata()
{
cout << x;
}
B(); // Constructor declaration
}
Parashar Technologies S P SHARMA CLASSES 9910707562
64 www.spsharmag.com www.parashartechnologies.com
MySpace::B::B() // Constructor definition
{
x=0;
}
The using directive
using keyword allows you to import an entire namespace into your program with a global scope. It can be
used to import a namespace into another namespace or any program.
Namespace1.h
namespace X
{
int x;
class Check
{
int i;
};
}
Namespace2.h
include "Namespace1.h";
namespace Y
{
using namespace X;
Check obj;
int y;
}
We imported the namespace X into namespace Y; hence class Check is available in namespace Y.
Parashar Technologies S P SHARMA CLASSES 9910707562
65 www.spsharmag.com www.parashartechnologies.com
Program.cpp
#include "Namespace2.h";
void test()
{
using Namespace Y;
Check obj2;
}
Hence, the using directive makes it a lot easier to use namespace, wherever you want.
The using declaration
When we use using directive, we import all the names in the namespace and they are available throughout
the program that is they have global scope.
But with using declaration, we import one specific name at a time which is available only inside the current
scope.
NOTE: Name imported with using declaration can override the name imported with using directive
Namespace.h
namespace X
{
void f() {}
void g() {}
}
namespace Y
{
void f() {}
void g() {}
}
Parashar Technologies S P SHARMA CLASSES 9910707562
66 www.spsharmag.com www.parashartechnologies.com
Program.cpp
#include "Namespace.h";
void h()
{
using namespace X; // using directive
using Y::f; // using declaration
f(); // calls f() of Y namespace
X::f(); // class f() of X namespace
}
In using declaration, we never mention the argument list of a function while importing it, hence if a
namespace has overloaded function, it will lead to ambiguity.
Static Keyword
Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated
storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime.
Static Keyword can be used with following,
1. Static variable in functions
2. Static Class Objects
3. Static member Variable in class
4. Static Methods in class
Static variables inside Functions
Static variables when used inside function are initialized only once, and then they hold there value even
through function calls.
These static variables are stored on static storage area, not in stack.
void counter()
{
static int count=0;
Parashar Technologies S P SHARMA CLASSES 9910707562
67 www.spsharmag.com www.parashartechnologies.com
cout << count++;
}
int main(0
{
for(int i=0;i<5;i++)
{
counter();
}
}
Output : 0 1 2 3 4
Let's se the same program's output without using static variable.
void counter()
{
int count=0;
cout << count++;
}
int main(0
{
for(int i=0;i<5;i++)
{
counter();
}
}
Output : 0 0 0 0 0
If we do not use static keyword, the variable count, is reinitialized every time when counter() function is
called, and gets destroyed each time when counter() functions ends. But, if we make it static, once initialized
count will have a scope till the end of main() function and it will carry its value through function calls too.
If you don't initialize a static variable, they are by default initialized to zero.
Parashar Technologies S P SHARMA CLASSES 9910707562
68 www.spsharmag.com www.parashartechnologies.com
Static class Objects
Static keyword works in the same way for class objects too. Objects declared static are allocated storage in
static storage area, and have scope till the end of program.
Static objects are also initialized using constructors like other normal objects. Assignment to zero, on using
static keyword is only for primitive data types, not for user defined data types.
class Abc
{
int i;
public:
Abc()
{
i=0;
cout << "constructor";
}
~Abc()
{
cout << "destructor";
}
};
void f()
{
static Abc obj;
}
int main()
{
Parashar Technologies S P SHARMA CLASSES 9910707562
69 www.spsharmag.com www.parashartechnologies.com
int x=0;
if(x==0)
{
f();
}
cout << "END";
}
Output: constructor END destructor
You must be thinking, why was destructor not called upon the end of the scope of if condition. This is
because object was static, which has scope till the program lifetime, hence destructor for this object was
called when main() exits.
Static data member in class
Static data members of class are those members which are shared by all the objects. Static data member has
a single piece of storage, and is not available as separate copy with each object, like other non-static data
members.
Static member variables (data members) are not initialized using constructor, because these are not
dependent on object initialization.
Also, it must be initialized explicitly, always outside the class. If not initialized, Linker will give error.
class X
{
static int i;
public:
X(){};
};
int X::i=1;
Parashar Technologies S P SHARMA CLASSES 9910707562
70 www.spsharmag.com www.parashartechnologies.com
int main()
{
X obj;
cout << obj.i; // prints value of i
}
Once the definition for static data member is made, user cannot redefine it. Though, arithmetic operations
can be performed on it.
Static Member Functions
These functions work for the class as whole rather than for a particular object of a class.
It can be called using an object and the direct member access . operator. But, its more typical to call a static
member function by itself, using class name and scope resolution :: operator.
Example :
class X
{
public:
static void f(){};
};
int main()
{
X::f(); // calling member function directly with class name
}
These functions cannot access ordinary data members and member functions, but only static data members
and static member functions.
It doesn't have any "this" keyword which is the reason it cannot access ordinary members. We will study
about "this" keyword later.
Parashar Technologies S P SHARMA CLASSES 9910707562
71 www.spsharmag.com www.parashartechnologies.com
Const Keyword
Constant is something that doesn't change. In C and C++ we use the keyword const to make program
elements constant. Const keyword can be used in many contexts in a C++ program. Const keyword can be
used with:
1. Variables
2. Pointers
3. Function arguments and return types
4. Class Data members
5. Class Member functions
6. Objects
1) Constant Variables
If you make any variable as constant, using const keyword, you cannot change its value. Also, the constant
variables must be initialized while declared.
int main
{
const int i = 10;
const int j = i+10; // Works fine
i++; // This leads to Compile time error
}
In this program we have made i as constant, hence if we try to change its value, compile time error is given.
Though we can use it for substitution.
2) Pointers with Const
Pointers can be made const too. When we use const with pointers, we can do it in two ways, either we can
apply const to what the pointer is pointing to, or we can make the pointer itself a const.
Parashar Technologies S P SHARMA CLASSES 9910707562
72 www.spsharmag.com www.parashartechnologies.com
Pointer to Const
This means that the pointer is pointing to a const variable.
const int* u;
Here, u is a pointer that points to a const int. We can also write it like,
int const* v;
still it has the same meaning. In this case also, v is a pointer to an int which is const.
Const pointer
To make the pointer const, we have to put the const keyword to the right of the * .
int x = 1;
int* const w = &x;
Here, w is a pointer, which is const that points to an int. Now we can't change the pointer but can change the
value that it points to.
NOTE: We can also have a const pointer pointing to a const variable.
const int* const x;
3) Const Function Arguments and Return types
We can make the return type or arguments of a function as const. Then we cannot change any of them.
void f(const int i)
{
i++; // Error
}
const int g()
{
Parashar Technologies S P SHARMA CLASSES 9910707562
73 www.spsharmag.com www.parashartechnologies.com
return 1;
}
Some Important points to remember
1. For built in types, returning a const or non-const, doesn't make any difference.
const int h()
{
return 1;
}
it main()
{
const int j = h();
int k = h();
}
Both j and k will be assigned 1. No error will occur.
2. For user defined data types, returning const, will prevent its modification.
3. Temporary objects created while program execution are always of const type.
4. If a function has a non-const parameter, it cannot be passed a const argument while making a call.
void t(int*) { }
If we pass a const int* argument, it will give error.
5. But, a function which has a const type parameter, can be passed a const type argument as well as a non-
const argument.
void g(const int*) {}
This function can have a int* as well as const int* type argument.
Parashar Technologies S P SHARMA CLASSES 9910707562
74 www.spsharmag.com www.parashartechnologies.com
4) Const class Data members
These are data variables in class which are made const. They are not initialized during declaration. Their
initialization occurs in the constructor.
class Test
{
const int i;
public:
Test (int x)
{
i=x;
}
};
int main()
{
Test t(10);
Test s(20);
}
In this program, i is a const data member, in every object its independent copy is present, hence it is
initialized with each object using constructor. Once initialized, it cannot be changed.
5) Const class Object
When an object is declared or created with const, its data members can never be changed, during object's
lifetime.
Syntax :
const class_name object;
Parashar Technologies S P SHARMA CLASSES 9910707562
75 www.spsharmag.com www.parashartechnologies.com
Const class Member function
A const member function never modifies data members in an object.
Syntax :
return_type function_name() const;
Example for const Object and const Member function
class X
{
int i;
public:
X(int x) // Constructor
{ i=x; }
int f() const // Constant function
{ i++; }
int g()
{ i++; }
};
int main()
{
X obj1(10); // Non const Object
const X obj2(20); // Const Object
obj1.f(); // No error
obj2.f(); // No error
Parashar Technologies S P SHARMA CLASSES 9910707562
76 www.spsharmag.com www.parashartechnologies.com
cout << obj1.i << obj2.i ;
obj1.g(); // No error
obj2.g(); // Compile time error
}
Output : 10 20
Here, we can see, that const member function never changes data members of class, and it can be used with
both const and non-const object. But a const object can't be used with a member function which tries to
change its data members.
Mutable Keyword
Mutable keyword is used with member variables of class, which we want to change even if the object is of
const type. Hence, mutable data members of a const objects can be modified.
class Z
{
int i;
mutable int j;
public:
Z()
{i=0; j=0;}
void f() const
{ i++; // Error
j++; // Works, because j is Mutable
}
};
int main(0
{
Parashar Technologies S P SHARMA CLASSES 9910707562
77 www.spsharmag.com www.parashartechnologies.com
const Z obj;
obj.f();
}
References in C++
References are like constant pointers that are automatically dereference. It is a new name given to an
existing storage. So when you are accessing the reference, you are actually accessing that storage.
int main()
{ int y=10;
int &r = y; // r is a reference to int y
cout << r;
}
Output : 10
There is no need to use the * to dereference a reference variable.
Difference between Reference and Pointer
References Pointers
Reference must be initialized when it is created. Pointers can be initialized any time.
Once initialized, we cannot reinitialize a reference. Pointers can be reinitialized any number of time.
You can never have a NULL reference. Pointers can be NULL.
Reference is automatically dereferenced. * is used to dereference a pointer.
Parashar Technologies S P SHARMA CLASSES 9910707562
78 www.spsharmag.com www.parashartechnologies.com
References in Functions
References are generally used for function argument lists and function return values, just like pointers.
Rules for using Reference in Functions
1. When we use reference in argument list, we must keep in mind that any change to the reference inside
the function will cause change to the original argument outside the function.
2. When we return a reference from a function, you should see that whatever the reference is connected
to shouldn't go out of scope when function ends. Either make that global or static
Example to explain use of References
int* first (int* x)
{ (*x++);
return x; // SAFE, x is outside this scope
}
int& second (int& x)
{ x++;
return x; // SAFE, x is outside this scope
}
int& third ()
{ int q;
return q; // ERROR, scope of q ends here
}
int& fourth ()
{ static int x;
Parashar Technologies S P SHARMA CLASSES 9910707562
79 www.spsharmag.com www.parashartechnologies.com
return x; // SAFE, x is static, hence lives till the end.
}
int main()
{
int a=0;
first(&a); // UGLY and explicit
second(a); // CLEAN and hidden
}
We have four different functions in the above program.
first() takes a pointer as argument and returns a pointer, it will work fine. The returning pointer points to
variable declared outside first(), hence it will be valid even after the first() ends.
Similarly, second() will also work fine. The returning reference is connected to valid storage, that is int
a in this case.
But in case of third(), we declare a variable q inside the function and try to return a reference
connected to it. But as soon as function third() ends, the local variable q is destroyed, hence nothing is
returned.
To re-modify above problem, we make x as static in function fourth(), giving it a lifetime till main() ends,
hence now a reference connected to x will be valid when returned.
Const Reference
Const reference is used in function arguments to prevent the function from changing the argument.
void g(const int& x)
{ x++; } // ERROR
int main()
{
Parashar Technologies S P SHARMA CLASSES 9910707562
80 www.spsharmag.com www.parashartechnologies.com
int i=10;
g(i);
}
We cannot change the argument in the function because it is passed as const reference.
Argument Passing Guidelines
Usually call by value is used during function call just to save our object or variable from being changed or
modified, but whenever we pass an argument by value, its new copy is created. If we pass an object as
argument then a copy of that object is created (constructor and destructors called), which affects efficiency.
Hence, we must use const reference type arguments. When we use, const reference, only an address is
passed on stack, which is used inside the function and the function cannot change our argument because it is
of const type.
So using const reference type argument reduces overhead and also saves our argument from being changed.
Copy Constructor in C++
Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a
class type. It is usually of the form X (X&), where X is the class name. The compiler provides a default Copy
Constructor to all the classes.
Syntax of Copy Constructor
class-name (class-name &)
{
. . . .
}
As it is used to create an object, hence it is called a constructor. And, it creates a new object, which is exact
copy of the existing copy, hence it is called copy constructor.
Parashar Technologies S P SHARMA CLASSES 9910707562
81 www.spsharmag.com www.parashartechnologies.com
Pointers to class members
Just like pointers to normal variables and functions, we can have pointers to class member functions and
member variables.
Defining a pointer of class type
We can define pointer of class type, which can be used to point to class objects.
class Simple
{
public:
int a;
};
int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;
Parashar Technologies S P SHARMA CLASSES 9910707562
82 www.spsharmag.com www.parashartechnologies.com
cout << obj.a;
cout << ptr->a; // Accessing member with pointer
}
Here you can see that we have declared a pointer of class type which points to class's object. We can access
data members and member functions using pointer name with arrow -> symbol.
Pointer to Data Members of class
We can use pointer to point to class's data members (Member variables).
Syntax for Declaration:
datatype class_name :: *pointer_name ;
Syntax for Assignment :
pointer_name = &class_name :: datamember_name ;
Both declaration and assignment can be done in a single statement too.
datatype class_name::*pointer_name = &class_name::datamember_name ;
Using with Objects
For accessing normal data members we use the dot . operator with object and -> qith pointer to object.
But when we have a pointer to data member, we have to dereference that pointer to get what its pointing to,
hence it becomes,
Object.*pointerToMember
and with pointer to object, it can be accessed by writing,
ObjectPointer->*pointerToMember
Lets take an example, to understand the complete concept.
class Data
{
Parashar Technologies S P SHARMA CLASSES 9910707562
83 www.spsharmag.com www.parashartechnologies.com
public:
int a;
void print() { cout << "a is="<< a; }
};
int main()
{
Data d, *dp;
dp = &d; // pointer to object
int Data::*ptr=&Data::a; // pointer to data member 'a'
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
}
Output : a is=10 a is=20
The syntax is very tough, hence they are only used under special circumstances.
Pointer to Member Functions
Pointers can be used to point to class's Member functions.
Syntax :
return_type (class_name::*ptr_name) (argument_type) = &class_name::function_name ;
Below is an example to show how we use ppointer to member functions.
class Data
Parashar Technologies S P SHARMA CLASSES 9910707562
84 www.spsharmag.com www.parashartechnologies.com
{ public:
int f (float) { return 1; }
};
int (Data::*fp1) (float) = &Data::f; // Declaration and assignment
int (Data::*fp2) (float); // Only Declaration
int main(0
{
fp2 = &Data::f; // Assignment inside main()
}
Some Points to remember
1. You can change the value and behaviour of these pointers on runtime. That means, you can point it to
other member function or member variable.
2. To have pointer to data member and member functions you need to make them public.
Overview of Inheritance
Inheritance is the capability of one class to acquire properties and characteristics from another class. The
class whose properties are inherited by other class is called the Parent or Base or Super class. And, the class
which inherits properties of other class is called Child or Derived or Sub class.
Inheritance makes the code reusable. When we inherit an existing class, all its methods and fields become
available in the new class, hence code is reused.
NOTE: All members of a class except Private, are inherited
Purpose of Inheritance
Parashar Technologies S P SHARMA CLASSES 9910707562
85 www.spsharmag.com www.parashartechnologies.com
1. Code Reusability
2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword
Basic Syntax of Inheritance
class Subclass_name : access_mode Superclass_name
While defining a subclass like this, the super class must be already defined or at least declared before the
subclass declaration.
Access Mode is used to specify, the mode in which the properties of superclass will be inherited into subclass,
public, private or protected.
Example of Inheritance
class Animal
{ public:
int legs = 4;
};
Parashar Technologies S P SHARMA CLASSES 9910707562
86 www.spsharmag.com www.parashartechnologies.com
class Dog : public Animal
{ public:
int tail = 1;
};
int main()
{
Dog d;
cout << d.legs;
cout << d.tail;
}
Output : 4 1
Inheritance Visibility Mode
Depending on Access modifier used while inheritance, the availability of class members of Super class in the
sub class changes. It can either be private, protected or public.
1) Public Inheritance
This is the most used inheritance mode. In this the protected member of super class becomes protected
members of sub class and public becomes public.
class Subclass : public Superclass
2) Private Inheritance
In private mode, the protected and public members of super class become private members of derived class.
class Subclass : Superclass // By default its private inheritance
3) Protected Inheritance
In protected mode, the public and protected member of Super class becomes protected members of Sub
class.
Parashar Technologies S P SHARMA CLASSES 9910707562
87 www.spsharmag.com www.parashartechnologies.com
class subclass : protected Superclass
Table showing all the Visibility Modes
Base class
Derived Class
Public Mode Private Mode Protected Mode
Private Not Inherited Not Inherited Not Inherited
Protected Protected Private Protected
Public Public Private Protected
Types of Inheritance
In C++, we have 5 different types of Inheritance. Namely,
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)
Single Inheritance
In this type of inheritance one derived class inherits from only one base class. It is the simplest form of
Inheritance.
Parashar Technologies S P SHARMA CLASSES 9910707562
88 www.spsharmag.com www.parashartechnologies.com
Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or more than two base classes.
Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherit from a single base class.
Parashar Technologies S P SHARMA CLASSES 9910707562
89 www.spsharmag.com www.parashartechnologies.com
Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which in turn inherits from some other class.
The Super class for one is sub class for the other.
Hybrid (Virtual) Inheritance
Hybrid Inheritance is combination of Hierarchical and Multilevel Inheritance.
Parashar Technologies S P SHARMA CLASSES 9910707562
90 www.spsharmag.com www.parashartechnologies.com
Order of Constructor Call
Base class constructors are always called in the derived class constructors. Whenever you create derived class
object, first the base class default constructor is executed and then the derived class's constructor finishes
execution.
Points to Remember
1. Whether derived class's default constructor is called or parameterized is called, base class's default
constructor is always called inside them.
2. To call base class's parameterized constructor inside derived class's parameterized constructor, we must
mention it explicitly while declaring derived class's parameterized constructor.
Base class Default Constructor in Derived class Constructors
class Base
{ int x;
public:
Base() { cout << "Base default constructor"; }
};
Parashar Technologies S P SHARMA CLASSES 9910707562
91 www.spsharmag.com www.parashartechnologies.com
class Derived : public Base
{ int y;
public:
Derived() { cout << "Derived default constructor"; }
Derived(int i) { cout << "Derived parameterized constructor"; }
};
int main()
{
Base b;
Derived d1;
Derived d2(10);
}
You will see in the above example that with both the object creation of the Derived class, Base class's default
constructor is called.
Base class Parameterized Constructor in Derived class Constructor
We can explicitly mention to call the Base class's parameterized constructor when Derived class's
parameterized constructor is called.
class Base
{ int x;
public:
Base(int i)
{ x = i;
cout << "Base Parameterized Constructor";
}
};
Parashar Technologies S P SHARMA CLASSES 9910707562
92 www.spsharmag.com www.parashartechnologies.com
class Derived : public Base
{ int y;
public:
Derived(int j) : Base(j)
{ y = j;
cout << "Derived Parameterized Constructor";
}
};
int main()
{
Derived d(10) ;
cout << d.x ; // Output will be 10
cout << d.y ; // Output will be 10
}
Why is Base class Constructor called inside Derived class ?
Constructors have a special job of initializing the object properly. A Derived class constructor has access only
to its own class members, but a Derived class object also have inherited property of Base class, and only base
class constructor can properly initialize base class members. Hence all the constructors are called; else object
wouldn't be constructed properly.
Constructor call in Multiple Inheritance
Its almost the same, all the Base class's constructors are called inside derived class's constructor, in the same
order in which they are inherited.
class A : public B, public C ;
Parashar Technologies S P SHARMA CLASSES 9910707562
93 www.spsharmag.com www.parashartechnologies.com
In this case, first class B constructor will be executed, then class C constructor and then class A constructor.
Upcasting in C++
Upcasting is using the Super class's reference or pointer to refer to a Sub class's object. Or we can say that,
the act of converting a Sub class's reference or pointer into its Super class's reference or pointer is called
Upcasting.
class Super
{ int x;
public:
void funBase() { cout << "Super function"; }
};
class Sub : public Super
{ int y;
};
int main()
{
Super* ptr; // Super class pointer
Sub obj;
ptr = &obj;
Parashar Technologies S P SHARMA CLASSES 9910707562
94 www.spsharmag.com www.parashartechnologies.com
Super &ref; // Super class's reference
ref=obj;
}
The opposite of Upcasting is Downcasting, in which we convert Super class's reference or pointer into
derived class's reference or pointer. We will study more about Downcasting later
Functions that are never Inherited
Constructors and Destructors are never inherited and hence never override.
Also, assignment operator = is never inherited. It can be overloaded but can't be inherited by sub class.
Inheritance and Static Functions
1. They are inherited into the derived class.
2. If you redefine a static member function in derived class, all the other overloaded functions in base class
are hidden.
3. Static Member functions can never be virtual. We will study about Virtual incoming topics.
Hybrid Inheritance and Virtual Class
In Multiple Inheritance, the derived class inherits from more than one base class. Hence, in Multiple
Inheritance there are lot chances of ambiguity.
class A
{ void show(); };
class B:public A {};
Parashar Technologies S P SHARMA CLASSES 9910707562
95 www.spsharmag.com www.parashartechnologies.com
class C:public A {};
class D:public B, public C {};
int main()
{
D obj;
obj.show();
}
In this case both class B and C inherits function show() from class A. Hence class D has two inherited copies of
function show(). In main() function when we call function show(), then ambiguity arises, because compiler
doesn't know which show() function to call. Hence we use Virtual keyword while inheriting class.
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};
Now by adding virtual keyword, we tell compiler to call any one out of the two show() functions.
Hybrid Inheritance and Constructor call
As we all know that whenever a derived class object is instantiated, the base class constructor is always
called. But in case of Hybrid Inheritance, as discussed in above example, if we create an instance of class D,
then following constructors will be called:
Before class D's constructor, constructors of its super classes will be called, hence constructors of class B,
class C and class A will be called.
When constructors of class B and class C are called, they will again make a call to their super class's
constructor.
Parashar Technologies S P SHARMA CLASSES 9910707562
96 www.spsharmag.com www.parashartechnologies.com
This will result in multiple calls to the constructor of class A, which is undesirable. As there is a single instance
of virtual base class which is shared by multiple classes that inherit from it, hence the constructor of the base
class is only called once by the constructor of concrete class, which in our case is class D.
If there is any call for initializing the constructor of class A in class B or class C, while creating object of class D,
all such calls will be skipped.
Polymorphism
Polymorphism means having multiple forms of one thing. In inheritance, polymorphism is done, by method
overriding, when both super and sub class have member function with same declaration but different
definition.
Function Overriding
If we inherit a class into the derived class and provide a definition for one of the base class's function again
inside the derived class, then that function is said to be overridden, and this mechanism is called Function
Overriding
Requirements for Overriding
1. Inheritance should be there. Function overriding cannot be done within a class. For this we require a
derived class and a base class.
2. Function that is redefined must have exactly the same declaration in both base and derived class, that
means same name, same return type and same parameter list.
Example of Function Overriding
class Base
{
public:
void show()
Parashar Technologies S P SHARMA CLASSES 9910707562
97 www.spsharmag.com www.parashartechnologies.com
{
cout << "Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
In this example, function show() is overridden in the derived class. Now let us study how these overridden
functions are called in main() function.
Function Call Binding with class Objects
Connecting the function call to the function body is called Binding. When it is done before the program is run,
it’s called Early Binding or Static Binding or Compile-time Binding.
class Base
{
public:
void shaow()
{
cout << "Base class\t";
}
};
class Derived:public Base
{
Parashar Technologies S P SHARMA CLASSES 9910707562
98 www.spsharmag.com www.parashartechnologies.com
public:
void show()
{
cout << "Derived Class";
}
}
int mian()
{
Base b; //Base class object
Derived d; //Derived class object
b.show(); //Early Binding Ocuurs
d.show();
}
Output : Base class Derived class
In the above example, we are calling the overrided function using Base class and Derived class object. Base
class object will call base version of the function and derived class's object will call the derived version of the
function.
Function Call Binding using Base class Pointer
But when we use a Base class's pointer or reference to hold Derived class's object, then Function call Binding
gives some unexpected results.
class Base
{
public:
void shaow()
{
cout << "Base class";
Parashar Technologies S P SHARMA CLASSES 9910707562
99 www.spsharmag.com www.parashartechnologies.com
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
int mian()
{
Base* b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show(); //Early Binding Ocuurs
}
Output : Base class
In the above example, although, the object is of Derived class, still Base class's method is called. This happens
due to Early Binding.
Compiler on seeing Base class's pointer, set call to Base class's show() function, without knowing the actual
object type.
Virtual Functions
Virtual Function is a function in base class, which is overrided in the derived class, and which tells the
compiler to perform Late Binding on this function.
Virtual Keyword is used to make a member function of the base class Virtual.
Parashar Technologies S P SHARMA CLASSES 9910707562
100 www.spsharmag.com www.parashartechnologies.com
Late Binding
In Late Binding function call is resolved at runtime. Hence, now compiler determines the type of object at
runtime, and then binds the function call. Late Binding is also called Dynamic Binding or Runtime Binding.
Problem without Virtual Keyword
class Base
{
public:
void show()
{
cout << "Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
int main()
{
Base* b; //Base class pointer
Derived d; //Derived class object
Parashar Technologies S P SHARMA CLASSES 9910707562
101 www.spsharmag.com www.parashartechnologies.com
b = &d;
b->show(); //Early Binding Ocuurs
}
Output: Base class
When we use Base class's pointer to hold Derived class's object, base class pointer or reference will always
call the base version of the function
Using Virtual Keyword
We can make base class's methods virtual by using virtual keyword while declaring them. Virtual keyword
will lead to Late Binding of that method.
class Base
{
public:
virtual void show()
{
cout << "Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
int main()
Parashar Technologies S P SHARMA CLASSES 9910707562
102 www.spsharmag.com www.parashartechnologies.com
{
Base* b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show(); //Late Binding Ocuurs
}
Output : Derived class
On using Virtual keyword with Base class's function, Late Binding takes place and the derived version of
function will be called, because base class pointer pointes to Derived class object.
Using Virtual Keyword and Accessing Private Method of Derived class
We can call private function of derived class from the base class pointer with the help of virtual keyword.
Compiler checks for access specifier only at compile time. So at run time when late binding occurs it does not
check whether we are calling the private function or public function.
#include
using namespace std;
class A
{
public:
virtual void show()
{
cout << "Base class\n";
}
};
class B: public A
{
Parashar Technologies S P SHARMA CLASSES 9910707562
103 www.spsharmag.com www.parashartechnologies.com
private:
virtual void show()
{
cout << "Derived class\n";
}
};
int main()
{
A *a;
B b;
a = &b;
a -> show();
}
Output: Derived class
Mechanism of Late Binding
Parashar Technologies S P SHARMA CLASSES 9910707562
104 www.spsharmag.com www.parashartechnologies.com
To accomplish late binding, Compiler creates VTABLEs, for each class with virtual function. The address of
virtual functions is inserted into these tables. Whenever an object of such class is created the compiler
secretly inserts a pointer called vpointer, pointing to VTABLE for that object. Hence when function is called,
compiler is able to resolve the call by binding the correct function using the vpointer.
Important Points to Remember
1. Only the Base class Method's declaration needs the Virtual Keyword, not the definition.
2. If a function is declared as virtual in the base class, it will be virtual in all its derived classes.
3. The address of the virtual Function is placed in the VTABLE and the compiler uses VPTR(vpointer) to
point to the Virtual Function.
4.
Parashar Technologies S P SHARMA CLASSES 9910707562
105 www.spsharmag.com www.parashartechnologies.com
Abstract Class
Abstract Class is a class which contains at least one Pure Virtual function in it. Abstract classes are used to
provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide definition to the
pure virtual function, otherwise they will also become abstract class.
Characteristics of Abstract Class
1. Abstract class cannot be instantiated, but pointers and references of Abstract class type can be created.
2. Abstract class can have normal functions and variables along with a pure virtual function.
3. Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
4. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will become
Abstract too.
Pure Virtual Functions
Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and ends
with = 0 . Here is the syntax for a pure virtual function,
virtual void f() = 0;
Example of Abstract Class
class Base //Abstract base class
{
public:
virtual void show() = 0; //Pure Virtual Function
};
class Derived:public Base
{
Parashar Technologies S P SHARMA CLASSES 9910707562
106 www.spsharmag.com www.parashartechnologies.com
public:
void show()
{ cout << "Implementation of Virtual Function in Derived class"; }
};
int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
Output : Implementation of Virtual Function in Derived class
In the above example Base class is abstract, with pure virtual show() function, hence we cannot create object
of base class.
Why can't we create Object of Abstract Class?
When we create a pure virtual function in Abstract class, we reserve a slot for a function in the
VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such
class and will display an error message whenever you try to do so.
Pure Virtual definitions
Pure Virtual functions can be given a small definition in the Abstract class, which you want all the derived
classes to have. Still you cannot create object of Abstract class.
Parashar Technologies S P SHARMA CLASSES 9910707562
107 www.spsharmag.com www.parashartechnologies.com
Also, the Pure Virtual function must be defined outside the class definition. If you will define it inside the
class definition, complier will give an error. Inline pure virtual definition is Illegal.
class Base //Abstract base class
{
public:
virtual void show() = 0; //Pure Virtual Function
};
void Base :: show() //Pure Virtual definition
{
cout << "Pure Virtual definition\n";
}
class Derived:public Base
{
public:
void show()
{ cout << "Implementation of Virtual Function in Derived class"; }
};
int main()
{
Base *b;
Derived d;
b = &d;
b->show();
}
Output :
Parashar Technologies S P SHARMA CLASSES 9910707562
108 www.spsharmag.com www.parashartechnologies.com
Pure Virtual definition
Implementation of Virtual Function in Derived class
Virtual Destructors
Destructors in the Base class can be Virtual. Whenever Upcasting is done, Destructors of the Base class must be made virtual for proper destruction of the object when the program exits.
NOTE: Constructors are never Virtual, only Destructors can be Virtual.
Upcasting without Virtual Destructor
Lets first see what happens when we do not have a virtual Base class destructor.
class Base
{
public:
~Base() {cout << "Base Destructor\t"; }
};
class Derived:public Base
{
public:
~Derived() { cout<< "Derived Destructor"; }
};
int main()
{
Base* b = new Derived; //Upcasting
delete b;
}
Output : Base Destructor
Parashar Technologies S P SHARMA CLASSES 9910707562
109 www.spsharmag.com www.parashartechnologies.com
In the above example, delete b will only call the Base class destructor, which is undesirable because, then the object of Derived class remains undestructed, because its destructor is never called. Which results in
memory leak.
Upcasting with Virtual Destructor
Now lets see. What happens when we have Virtual destructor in the base class?
class Base
{
public:
virtual ~Base() {cout << "Base Destructor\t"; }
};
class Derived:public Base
{
public:
~Derived() { cout<< "Derived Destructor"; }
};
int main()
{
Base* b = new Derived; //Upcasting
delete b;
}
Output :
Derived Destructor
Base Destructor
When we have Virtual destructor inside the base class, then first Derived class's destructor is called and then Base class's destructor is called, which is the desired behaviour.
Parashar Technologies S P SHARMA CLASSES 9910707562
110 www.spsharmag.com www.parashartechnologies.com
Pure Virtual Destructors
Pure Virtual Destructors are legal in C++. Also, pure virtual Destructors must be defined, which is
against the pure virtual behaviour.
The only difference between Virtual and Pure Virtual Destructor is, that pure virtual destructor will
make its Base class Abstract, hence you cannot create object of that class.
There is no requirement of implementing pure virtual destructors in the derived classes.
class Base
{
public:
virtual ~Base() = 0; //Pure Virtual Destructor
};
Base::~Base() { cout << "Base Destructor"; } //Definition of Pure Virtual Destructor
class Derived:public Base
{
public:
~Derived() { cout<< "Derived Destructor"; }
};
Operator Overloading Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type. For example '+' operator can be overloaded to perform addition on various data types, like
for Integer, String(concatenation) etc.
Parashar Technologies S P SHARMA CLASSES 9910707562
111 www.spsharmag.com www.parashartechnologies.com
Almost any operator can be overloaded in C++. However there are few operators which cannot be overloaded. Operator that are not overloaded are follows
scope operator - ::
sizeof
member selector - .
member pointer selector - *
ternary operator - ?:
Operator Overloading Syntax
Implementing Operator Overloading
Operator overloading can be done by implementing a function which can be :
1. Member Function
Parashar Technologies S P SHARMA CLASSES 9910707562
112 www.spsharmag.com www.parashartechnologies.com
2. Non-Member Function
3. Friend Function
Operator overloading function can be a member function if the Left operand is an Object of that class, but if the Left operand is different, then Operator overloading function must be a non-member function.
Operator overloading function can be made friend function if it needs access to the private and protected members of class.
Restrictions on Operator Overloading
Following are some restrictions to be kept in mind while implementing operator overloading.
1. Precedence and associatively of an operator cannot be changed.
2. Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains
binary etc.
3. No new operators can be created, only existing operators can be overloaded.
4. Cannot redefine the meaning of a procedure. You cannot change how integers are added.
Operator Overloading Examples
Almost all the operators can be overloaded in infinite different ways. Following are some examples to learn
more about operator overloading. All the examples are closely connected.
Overloading Arithmetic Operator
Arithmetic operators are most commonly used operator in C++. Almost all arithmetic operators can be
overloaded to perform arithmetic operation on user-defined data type. In the below example we have
overridden the + operator, to add to Time (hh:mm:ss) objects.
Parashar Technologies S P SHARMA CLASSES 9910707562
113 www.spsharmag.com www.parashartechnologies.com
Example: overloading '+' Operator to add two time object
#include< iostream.h>
#include< conio.h>
class time
{
int h,m,s;
public:
time()
{
h=0, m=0; s=0;
}
void getTime();
void show()
{
cout<< h<< ":"<< m<< ":"<< s;
}
time operator+(time); //overloading '+' operator
};
time time::operator+(time t1) //operator function
{
time t;
int a,b;
a=s+t1.s;
t.s=a%60;
b=(a/60)+m+t1.m;
t.m=b%60;
t.h=(b/60)+h+t1.h;
t.h=t.h%12;
return t;
Parashar Technologies S P SHARMA CLASSES 9910707562
114 www.spsharmag.com www.parashartechnologies.com
}
void time::getTime()
{
cout<<"\n Enter the hour(0-11) ";
cin>>h;
cout<<"\n Enter the minute(0-59) ";
cin>>m;
cout<<"\n Enter the second(0-59) ";
cin>>s;
}
void main()
{
clrscr();
time t1,t2,t3;
cout<<"\n Enter the first time ";
t1.getTime();
cout<<"\n Enter the second time ";
t2.getTime();
t3=t1+t2; //adding of two time object using '+' operator
cout<<"\n First time ";
t1.show();
cout<<"\n Second time ";
t2.show();
cout<<"\n Sum of times ";
t3.show();
getch();
}
Parashar Technologies S P SHARMA CLASSES 9910707562
115 www.spsharmag.com www.parashartechnologies.com
Overloading I/O operator
Overloaded to perform input/output for user defined datatypes.
Left Operand will be of types ostream& and istream&
Function overloading this operator must be a Non-Member function because left operand is not an
Object of the class.
It must be a friend function to access private data members.
You have seen above that << operator is overloaded with ostream class object cout to print primitive type
value output to the screen. Similarly you can overload << operator in your class to print user-defined type to
screen. For example we will overload << in time class to display time object using cout .
time t1(3,15,48);
cout << t1;
NOTE: When the operator does not modify its operands, the best way to overload the operator is via friend
function.
Example: overloading '<<' Operator to print time object
#include< iostream.h>
#include< conio.h>
class time
{
int hr,min,sec;
public:
time()
{
hr=0, min=0; sec=0;
}
time(int h,int m, int s)
Parashar Technologies S P SHARMA CLASSES 9910707562
116 www.spsharmag.com www.parashartechnologies.com
{
hr=h, min=m; sec=s;
}
friend ostream& operator << (ostream &out, time &tm); //overloading '<<' operator
};
ostream& operator<< (ostream &out, time &tm) //operator function
{
out << "Time is " << tm.hr << "hour : " << tm.min << "min : " << tm.sec << "sec";
return out;
}
void main()
{
time tm(3,15,45);
cout << tm;
}
Output
Time is 3 hour : 15 min : 45 sec
Overloading Relational operator
You can also overload Relational operator like == , != , >= , <= etc. to compare two user-defined object.
Example
class time
{
int hr,min,sec;
Parashar Technologies S P SHARMA CLASSES 9910707562
117 www.spsharmag.com www.parashartechnologies.com
public:
time()
{
hr=0, min=0; sec=0;
}
time(int h,int m, int s)
{
hr=h, min=m; sec=s;
}
friend bool operator==(time &t1, time &t2); //overloading '==' operator
};
bool operator== (time &t1, time &t2) //operator function
{
return ( t1.hr == t2.hr &&
t1.min == t2.min &&
t1.sec == t2.sec );
}
Copy constructor Vs. Assignment operator
Assignment operator is used to copy the values from one object to another already existing object. For
example
time tm(3,15,45); //tm object created and initialized
time t1; //t1 object created
t1 = tm; //initializing t1 using tm
Copy constructor is a special constructor that initializes a new object from an existing object.
time tm(3,15,45); //tm object created and initialized
time t1(tm); //t1 object created and initialized using tm object
Parashar Technologies S P SHARMA CLASSES 9910707562
118 www.spsharmag.com www.parashartechnologies.com
Data File Handling In C++
File. The information / data stored under a specific name on a storage device, is
called a file.
Stream. It refers to a sequence of bytes.
Text file. It is a file that stores information in ASCII characters. In text files,
each line of text is terminated with a special character known as EOL (End of
Line) character or delimiter character. When this EOL character is read or
written, certain internal translations take place.
Binary file. It is a file that contains information in the same format as it is held
in memory. In binary files, no delimiters are used for a line and no translations
occur here.
Classes for file stream operation
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Opening a file
OPENING FILE USING CONSTRUCTOR
ofstream outFile("sample.txt"); //output only
ifstream inFile(“sample.txt”); //input only
OPENING FILE USING open()
Stream-object.open(“filename”, mode)
ofstream outFile;
outFile.open("sample.txt");
ifstream inFile;
inFile.open("sample.txt"); File mode parameter Meaning
ios::app Append to end of file
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not exist
Parashar Technologies S P SHARMA CLASSES 9910707562
119 www.spsharmag.com www.parashartechnologies.com
ios::noreplace open fails if the file already exist
ios::trunc delete the contents of the file if it exist
All these flags can be combined using the bitwise operator OR (|). For example,
if we want to open the file example.bin in binary mode to add data we could do
it by the following call to member function open():
fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
Closing File
outFile.close();
inFile.close();
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly,
the function get() reads a single character form the associated stream.
example :
file.get(ch);
file.put(ch);
write() and read() function
write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION FUNCTION RETURN VALUE AND MEANING
eof() returns true (non zero) if end of file is encountered while reading;
otherwise return false(zero)
fail() return true when an input or output operation has failed
bad() returns true if an invalid operation is attempted or any unrecoverable
error has occurred.
good() returns true if no error has occurred.
File Pointers And Their Manipulation
Parashar Technologies S P SHARMA CLASSES 9910707562
120 www.spsharmag.com www.parashartechnologies.com
All i/o streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that points to the
element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that points to
the location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream
(which is itself derived from both istream and ostream).
These internal stream pointers that point to the reading or writing locations
within a stream can be manipulated using the following member functions: seekg() moves get pointer(input) to a specified location
seekp() moves put pointer (output) to a specified location
tellg() gives the current position of the get pointer
tellp() gives the current position of the put pointer
The other prototype for these functions is:
seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be
moved from the location specified by the parameter refposition. The refposition
takes one of the following three constants defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
example:
file.seekg(-10, ios::cur);
Basic Operation On Text File In C++ File I/O is a five-step process:
1. Include the header file fstream in the program.
2. Declare file stream object.
3. Open the file with the file stream object.
4. Use the file stream object with >>, <<, or other input/output functions.
5. Close the files.
Parashar Technologies S P SHARMA CLASSES 9910707562
121 www.spsharmag.com www.parashartechnologies.com
Following program shows how the steps might appear in program.
Program to write in a text file
#include <fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("out.txt");
char str[300] = "Time is a great teacher but
unfortunately it kills all its pupils. Berlioz";
//Write string to the file.
fout << str;
fout.close();
return 0;
}
Program to read from text file and display it
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout << ch;
}
fin.close();
return 0;
}
Program to count number of characters.
Parashar Technologies S P SHARMA CLASSES 9910707562
122 www.spsharmag.com www.parashartechnologies.com
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char ch;
while(!fin.eof())
{
fin.get(ch);
count++;
}
cout << "Number of characters in file are " << count;
fin.close();
return 0;
}
Program to count number of words
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char word[30];
while(!fin.eof())
{
fin >> word;
count++;
}
cout << "Number of words in file are " << count;
fin.close();
return 0;
}
Parashar Technologies S P SHARMA CLASSES 9910707562
123 www.spsharmag.com www.parashartechnologies.com
Program to count number of lines
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char str[80];
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
cout << "Number of lines in file are " << count;
fin.close();
return 0;
}
Program to copy contents of file to another file.
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout << ch;
}
Parashar Technologies S P SHARMA CLASSES 9910707562
124 www.spsharmag.com www.parashartechnologies.com
fin.close();
fout.close();
return 0;
}
Basic Operation On Binary File In C++
When data is stored in a file in the binary format, reading and writing
data is faster because no time is lost in converting the data from one format to
another format. Such files are called binary files. This following program
explains how to create binary files and also how to read, write, search, delete
and modify data from binary files. #include<iostream>
#include<fstream>
#include<cstdio>
using namespace std;
class Student
{
int admno;
char name[50];
public:
void setData()
{
cout << "\nEnter admission no. ";
cin >> admno;
cout << "Enter name of student ";
cin.getline(name,50);
}
void showData()
{
cout << "\nAdmission no. : " << admno;
cout << "\nStudent Name : " << name;
}
int retAdmno()
{
return admno;
}
};
/*
* function to write in a binary file.
*/
void write_record()
{
Parashar Technologies S P SHARMA CLASSES 9910707562
125 www.spsharmag.com www.parashartechnologies.com
ofstream outFile;
outFile.open("student.dat", ios::binary | ios::app);
Student obj;
obj.setData();
outFile.write((char*)&obj, sizeof(obj));
outFile.close();
}
/*
* function to display records of file
*/
void display()
{
ifstream inFile;
inFile.open("student.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}
inFile.close();
}
/*
* function to search and display from binary file
*/
void search(int n)
{
ifstream inFile;
inFile.open("student.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() == n)
{
obj.showData();
}
}
Parashar Technologies S P SHARMA CLASSES 9910707562
126 www.spsharmag.com www.parashartechnologies.com
inFile.close();
}
/*
* function to delete a record
*/
void delete_record(int n)
{
Student obj;
ifstream inFile;
inFile.open("student.dat", ios::binary);
ofstream outFile;
outFile.open("temp.dat", ios::out | ios::binary);
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() != n)
{
outFile.write((char*)&obj, sizeof(obj));
}
}
inFile.close();
outFile.close();
remove("student.dat");
rename("temp.dat", "student.dat");
}
/*
* function to modify a record
*/
void modify_record(int n)
{
fstream file;
file.open("student.dat",ios::in | ios::out);
Student obj;
while(file.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() == n)
{
cout << "\nEnter the new details of student";
obj.setData();
Parashar Technologies S P SHARMA CLASSES 9910707562
127 www.spsharmag.com www.parashartechnologies.com
int pos = -1 * sizeof(obj);
file.seekp(pos, ios::cur);
file.write((char*)&obj, sizeof(obj));
}
}
file.close();
}
int main()
{
//Store 4 records in file
for(int i = 1; i <= 4; i++)
write_record();
//Display all records
cout << "\nList of records";
display();
//Search record
cout << "\nSearch result";
search(100);
//Delete record
delete_record(100);
cout << "\nRecord Deleted";
//Modify record
cout << "\nModify Record 101 ";
modify_record(101);
return 0;
}