C++ Notes PDF
C++ Notes PDF
Inheritance
Inheritance is the mechanism by which one class can inherit the properties of another. It allows a
hierarchy of classes to be build, moving from the most general to the most specific. When one class is
inherited by another, the class that is inherited is called the base class. The inheriting class is called
Introduction the derived class. In general, the process of inheritance begins with the definition of a base class. The
base class defines all qualities that will be common to any derived class. . In OOPs, the concept of
Object oriented Programming inheritance provides the idea of reusability. In essence, the base class represent the most general
description of a set of traits. The derived class inherits those general traits and adds properties that are
Object oriented Programming is defined as an approach that provides a way of modularizing specific to that class.
programs by creating partitioned memory area for both data and functions that can be used as
6. Polymorphism
templates for creating copies of such modules on demand. Writing object-oriented programs involves
Polymorphism (from the Greek, meaning “many forms”) is a feature that allows one interface to be
creating classes, creating objects from those classes, and creating applications, which are stand-alone
used for a general class of actions. The specific action is determined by the exact nature of the
executable programs that use those objects. After being created, classes can be reused over and over
situation. The concept of polymorphism is often expressed by the phrase “one interface, multiple
again to develop new programs. Thinking in an object-oriented manner involves envisioning program
methods.” This means that it is possible to design a generic interface to a group of related activities.
components as objects that belong to classes and are similar to concrete objects in the real world;
This helps reduce complexity by allowing the same interface to be used to specify a general class of
then, you can manipulate the objects and have them interrelate with each other to achieve a desired
action. It is the compiler’s job to select the specific action as it applies to each situation.
result.
1. Class
A class is a user defined data type. A class is a logical abstraction. It is a template that defines the
Compile time Run time
form of an object. A class specifies both code and data. It is not until an object of that class has been
Polymorphism Polymorphism
created that a physical representation of that class exists in memory. When you define a class, you
declare the data that it contains and the code that operates on that data. Data is contained in instance
variables defined by the class known as data members, and code is contained in functions known as
member functions. The code and data that constitute a class are called members of the class. Function Operator Virtual
overloading overloading functions
2. Object
An object is an identifiable entity with specific characteristics and behavior. An object is said to be an
In compile time polymorphism, the compiler is able to select the appropriate function for a particular
instance of a class. Defining an object is similar to defining a variable of any data type. Space is set
call at compile time. In C++, it is possible to use one function name for many different purposes. This
aside for it in memory.
type of polymorphism is called function overloading. Polymorphism can also be applied to operators.
3. Encapsulation In that case, it is called operator overloading.
Encapsulation is a programming mechanism that binds together code and the data it manipulates, and In run time polymorphism, the compiler selects the appropriate function for a particular call while the
that keeps both safe from outside interference and misuse. C++’s basic unit of encapsulation is the program is running. C++ supports a mechanism known as virtual functions to achieve run time
class. Within a class, code or data or both may be private to that object or public. Private code or data polymorphism.
is known to and accessible by only another part of the object. That is, private code or data cannot be
accessed by a piece of the program that exists outside the object. When code or data is public, other Need for Object oriented Programming
parts of your program can access it even though it is defined within an object. Typically, the public
Object-oriented programming scales very well, from the most trivial of problems to the most complex
parts of an object are used to provide a controlled interface to the private elements of the object. This
tasks. It provides a form of abstraction that resonates with techniques people use to solve problems in
insulation of the data from direct access by the program is called data hiding.
their everyday life.
4. Data abstraction Object-oriented programming was developed because limitations were discovered in earlier
In object oriented programming, each object will have external interfaces through which it can be approaches to programming. There were two related problems. First, functions have unrestricted
made use of. There is no need to look into its inner details. The object itself may be made of many access to global data. Second, unrelated functions and data, the basis of the procedural paradigm,
smaller objects again with proper interfaces. The user needs to know the external interfaces only to provide a poor model of the real world.
make use of an object. The internal details of the objects are hidden which makes them abstract. The
technique of hiding internal details in an object is called data abstraction.
Benefits of Object oriented Programming The function named main is a special function in all C++ programs; it is the function called when the
1. Simplicity: Software objects model real world objects, so the complexity is reduced and the program is run. The execution of all C++ programs begins with the main function, regardless of
program structure is very clear. where the function is actually located within the code.
2. Modularity: Each object forms a separate entity whose internal workings are decoupled from other The open brace ({) indicates the beginning of main's function definition, and the closing brace (})
parts of the system. indicates its end.
3. Modifiability: It is easy to make minor changes in the data representation or the procedures in an The statement :
OO program. Changes inside a class do not affect any other part of a program, since the only public
cout<< “Simple C++ program without using class”;
interface that the external world has to a class is through the use of methods.
causes the string in quotation marks to be displayed on the screen. The identifier cout (pronounced as
4. Extensibility: adding new features or responding to changing operating environments can be
c out) denotes an object. It points to the standard output device namely the console monitor. The
solved by introducing a few new objects and modifying some existing ones.
operator << is called insertion operator. It directs the string on its right to the object on its left.
5. Maintainability: objects can be maintained separately, making locating and fixing problems easier.
The program ends with this statement:
6. Re-usability: objects can be reused in different programs.
return 0;
This causes zero to be returned to the calling process (which is usually the operating system).
Returning zero indicates that the program terminated normally. Abnormal program termination should
C++ be signaled by returning a nonzero value.
C++ is an object oriented programming language. It was developed by Bjarne Stroustrup in 1979 at
Bell Laboratories in Murray Hill, New Jersey. He initially called the new language "C with Classes."
However, in 1983 the name was changed to C++.
The general structure of C++ program with classes is shown as:
1. Documentation Section
C++ is a superset of C. Stroustrup built C++ on the foundation of C, including all of C’s features,
2. Preprocessor Directives or Compiler Directives Section
attributes, and benefits. Most of the features that Stroustrup added to C were designed to support
object-oriented programming .These features comprise of classes, inheritance, function overloading (i) Link Section
and operator overloading. C++ has many other new features as well, including an improved approach
to input/output (I/O) and a new way to write comments. (ii) Definition Section
C++ is used for developing applications such as editors, databases, personal file systems, networking 3. Global Declaration Section
utilities, and communication programs. Because C++ shares C’s efficiency, much high-performance 4. Class declaration or definition
systems software is constructed using C++.
5. Main C++ program function called main ( )
A Simple C++ Program
#include<iostream.h>
#include<conio.h> C++ keywords
int main() When a language is defined, one has to design a set of instructions to be used for communicating with
the computer to carry out specific operations. The set of instructions which are used in programming,
{ are called keywords. These are also known as reserved words of the language. They have a specific
meaning for the C++ compiler and should be used for giving specific instructions to the computer.
cout<< “Simple C++ program without using class”;
These words cannot be used for any other purpose, such as naming a variable. C++ is a case-sensitive
return 0; language, and it requires that all keywords be in lowercase. C++ keywords are:
}
Lines beginning with a hash sign (#) are directives read and interpreted by what is known as
the preprocessor. They are special lines interpreted before the compilation of the program itself
begins. In this case, the directive #include <iostream.h>, instructs the preprocessor to include a
section of standard C++ code, known as header iostream that allows to perform standard input and
output operations, such as writing the output of this program to the screen.
double(Double floating point) Stores real numbers in the range from 1.7x10
–308 to1.7x10308 with a precision of 15 digits.
bool(Boolean) can have only two possible values: true and false.
Void Valueless
C++ allows certain of the basic types to have modifiers preceding them. A modifier alters the
meaning of the base type so that it more precisely fits the needs of various situations. The data type
modifiers are: signed, unsigned, long and short
Identifiers
An identifier is a name assigned to a function, variable, or any other user-defined item. Identifiers can
be from one to several characters long.
Variable
Data types A variable is a named area in memory used to store values during program execution. Variables are
Data type defines size and type of values that a variable can store along with the set of operations that run time entities. A variable has a symbolic name and can be given a variety of values. When a
can be performed on that variable. C++ provides built-in data types that correspond to integers, variable is given a value, that value is actually placed in the memory space assigned to the variable.
characters, floating-point values, and Boolean values. There are the seven basic data types in C++ as All variables must be declared before they can be used. The general form of a declaration is:
shown below:
type variable_list;
Here, type must be a valid data type plus any modifiers, and variable_list may consist of one or more
Type Meaning identifier names separated by commas. Here are some declarations:
char(character) holds 8-bit ASCII characters
wchar_t(Wide character) holds characters that are part of large character sets int i,j,l;
int(Integer) represent integer numbers having no fractional part short int si;
float(floating point) stores real numbers in the range of about 3.4x10–38to unsigned int ui;
3.4x10 38,with a precision of seven digits.
double balance, profit, loss;
Typecasting
Typecasting is the concept of converting the value of one type into another type. For example, you
might have a float that you need to use in a function that requires an integer.
Implicit conversion
Almost every compiler makes use of what is called automatic typecasting. It automatically converts
one type into another type. If the compiler converts a type it will normally give a warning. For
example this warning: conversion from ‘double’ to ‘int’, possible loss of data. The problem with this
is, that you get a warning (normally you want to compile without warnings and errors) and you are not
in control. With control we mean, you did not decide to convert to another type, the compiler did.
Also the possible loss of data could be unwanted.
Unit –II // A Program to find whether a given number is even or odd using if … else statement
#include<iostream.h>
Control Structures
#include<conio.h>
Control structures allows to control the flow of program’s execution based on certain conditions C++
supports following basic control structures: int main()
cin>>n;
1) Selection Control structure:
Selection Control structures allows to control the flow of program’s execution depending upon the if(n%2==0)
state of a particular condition being true or false .C++ supports two types of selection statements :if cout<<”Even number”;
and switch. Condition operator (?:) can also be used as an alternative to the if statement.
else
A.1) If Statement: cout<<”Odd number”;
The syntax of an if statement in C++ is:
return 0;
if(condition)
}
{
// statement(s) will execute if the condition is true
A.2) The if...else Statement
} The syntax is shown as:
If the condition evaluates to true, then the block of code inside the if statement will be executed. If it if(condition){
evaluates to false, then the first set of code after the end of the if statement (after the closing curly
brace) will be executed. // statement(s) will execute if the condition is true
The syntax for a nested if statement is as follows: The expression must evaluate to a character or integer value. Floating-point expressions, for example,
are not allowed. The value of expression is tested, in order, against the values of the constants
if( condition 1){ specified in the case statements. When a match is found, the statement sequence associated with that
// Executes when the condition 1 is true case is executed until the break statement or the end of the switch statement is reached. The default
statement is executed if no matches are found. The default is optional and, if it is not present, no
if(condition 2){ action takes place if all matches fail.
// Executes when the condition 2 is true The break statement is one of C++'s jump statements. You can use it in loops as well as in the switch
statement. When break is encountered in a switch, program execution "jumps" to the line of code
}
following the switch statement.
}
Flowchart
The syntax of a while loop in C++ is: The conditional expression appears at the end of the loop, so the statement(s) in the loop execute once
before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the
while(condition){ statement(s) in the loop execute again. This process repeats until the given condition becomes false.
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true. After each
execution of the loop, the value of test expression is changed. When the condition becomes false,
program control passes to the line immediately following the loop.
Flowchart
#include<iostream.h>
#include<conio.h>
int main( ){
int i=1;
do
{ cout<<i ;
// A program to display numbers from 1 to 100
i++;
#include<iostream.h>
} while(i<=100);
#include<conio.h>
return 0;
int main(){
}
int i=1;
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself Function declaration — prototype:
(body of loop, then increment step, and then again condition). After the condition becomes false, the A function has to be declared before using it, in a manner similar to variables and constants. A
for loop terminates. function declaration tells the compiler about a function's name, return type, and parameters and how
to call the function. The general form of a C++ function declaration is as follows:
Flow Diagram
return_type function_name( parameter list );
Function definition
The function definition is the actual body of the function. The function definition consists of two parts
namely, function header and function body.
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{ body of the function }
Here, Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
// A program to display numbers from 1 to 100 Function Name: This is the actual name of the function.
#include<iostream.h> Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
#include<conio.h> parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
int main() { may contain no parameters.
int i ; Function Body: The function body contains a collection of statements that define what the function
does.
for (i=1;i<=100;i++)
{ Calling a Function
To use a function, you will have to call or invoke that function. To call a function, you simply need to
cout<<i ; pass the required parameters along with function name, and if function returns a value, then you can
store returned value.
return 0;
A c++ program calculating factorial of a number using functions
}
#include<iostream.h>
#include<conio.h>
int main(){
cin>>no; }
} cin>>a>>b;
int factorial(int n) //function definition cout << "The max is: " <<max(a,,b) << endl;
for(i=1;i<=n;i++){ }
fact=fact*i;
Macros Vs inline functions
} Preprocessor macros are just substitution patterns applied to your code. They can be used almost
return fact; anywhere in your code because they are replaced with their expansions before any compilation starts.
Inline functions are actual functions whose body is directly injected into their call site. They can only
} be used where a function call is appropriate.
Inline Functions inline functions are similar to macros (because the function code is expanded at the point of the call at
An inline function is a function that is expanded inline at the point at which it is invoked, instead of compile time), inline functions are parsed by the compiler, whereas macros are expanded by the
actually being called. The reason that inline functions are an important addition to C++ is that they preprocessor. As a result, there are several important differences:
allow you to create very efficient code. Each time a normal function is called, a significant amount of Inline functions follow all the protocols of type safety enforced on normal functions.
overhead is generated by the calling and return mechanism. Typically, arguments are pushed onto the
stack and various registers are saved when a function is called, and then restored when the function Inline functions are specified using the same syntax as any other function except that they
returns. The trouble is that these instructions take time. However, when a function is expanded inline, include the inline keyword in the function declaration.
none of those operations occur. Although expanding function calls in line can produce faster run Expressions passed as arguments to inline functions are evaluated once.
times, it can also result in larger code size because of duplicated code. For this reason, it is best to
inline only very small functions. inline is actually just a request, not a command, to the compiler. The In some cases, expressions passed as arguments to macros can be evaluated more than once.
compiler can choose to ignore it. Also, some compilers may not inline all types of functions. If a
macros are expanded at pre-compile time, you cannot use them for debugging, but you can
function cannot be inlined, it will simply be called as a normal function.
use inline functions.
A function can be defined as an inline function by prefixing the keyword inline to the function header
as given below: Reference variable
A reference variable is an alias, that is, another name for an already existing variable. Once a
inline function header {
reference is initialized with a variable, either the variable name or the reference name may be used to
function body refer to the variable. To declare a reference variable or parameter, precede the variable's name with
the &.The syntax for declaring a reference variable is:
}
datatype &Ref = variable name;
// A program illustrating inline function
Example:
#include<iostream.h>
int main(){
#include<conio.h>
int var1=10; //declaring simple variable
inline int max(int x, int y){
int & var2=var1; //declaring reference variable
if(x>y)
cout<<“\n value of var2 =” << var2;
return x;
return 0; Function Overloading
} Function overloading is the process of using the same name for two or more functions. Each
redefinition of the function must use either different types of parameters or a different number of
var2 is a reference variable to var1.Hence, var2 is an alternate name to var1.This code prints the value parameters. It is only through these differences that the compiler knows which function to call in any
of var2 exactly as that of var1. given situation. Overloaded functions can help reduce the complexity of a program by allowing
related operations to be referred to by the same name. To overload a function, simply declare and
Call by reference define all required versions. The compiler will automatically select the correct version based upon the
Arguments can be passed to functions in one of two ways: using call-by-value or call-by-reference. number and/or type of the arguments used to call the function. Two functions differing only in their
When using call-by-value, a copy of the argument is passed to the function. Call-by-reference passes return types cannot be overloaded.
the address of the argument to the function. By default, C++ uses call-by-value.
Example
Provision of the reference variables in c++ permits us to pass parameter to the functions by reference.
#include<iostream.h>
When we pass arguments by reference, the formal arguments in the called function become aliases to
the actual arguments in the calling function. This means that when the function is working with its #include<conio.h>
own arguments, it is actually working on the original data.
int sum(int p,int q,int r);
Example double sum(int l,double m);
#include <iostream.h>
float sum(float p,float q)
#include<conio.h>
int main(){
void swap(int &x, int &y); // function declaration
cout<<”sum=”<< sum(11,22,33); //calls func1
int main (){
cout<<”sum=”<< sum(10,15.5); //calls func2
int a = 10, b=20;
cout<<”sum=”<< sum(13.5,12.5); //calls func3
cout << "Before swapping”<<endl;
return 0;
cout<< “value of a :" << a <<” value of b :" << b << endl;
}
swap(a, b); //calling a function to swap the values.
int sum(int p,int q,int r){ //func1
cout << "After swapping”<<endl;
return(a+b+c);
cout<<” value of a :" << a<< “value of b :" << b << endl;
}
return 0;
double sum(int l,double m){ //func2
}
return(l+m);
void swap(int &x, int &y) { //function definition to swap the values.
}
int temp;
float sum(float p,float q){ //func3
temp = x;
return(p+q);
x = y;
}
y = temp;
} Default arguments
C++ allows a function to assign a parameter a default value when no argument corresponding to that
Output:
parameter is specified in a call to that function. The default value is specified in a manner
Before swapping value of a:10 value of b:20 syntactically similar to a variable initialization. All default parameters must be to the right of any
parameters that don't have defaults. We cannot provide a default value to a particular argument in the
After swapping value of a:20 value of b:10
middle of an argument list. When you create a function that has one or more default arguments, those
arguments must be specified only once: either in the function's prototype or in the function's definition
if the definition precedes the function's first use.
Default arguments are useful if you don’t want to go to the trouble of writing arguments that, for Unit-III
example, almost always have the same value. They are also useful in cases where, after a program is
written, the programmer decides to increase the capability of a function by adding another argument. Class
Using default arguments means that the existing function calls can continue to use the old number of
A class is a user defined data type. A class is a logical abstraction. It is a template that defines the
arguments, while new function calls can use more.
form of an object. A class specifies both code and data. It is not until an object of that class has been
Example created that a physical representation of that class exists in memory. When you define a class, you
declare the data that it contains and the code that operates on that data. Data is contained in instance
#include <iostream.h>
variables defined by the class known as data members, and code is contained in functions known as
#include<conio.h> member functions. The code and data that constitute a class are called members of the class. The
general form of class declaration is:
int sum(int a, int b=20){
class class-name {
return( a + b);
}
access-specifier:
#include<iostream.h>
#include<conio.h>
int a;
public:
void set_a(intnum);
int get_a( );
};
Object int main(){
An object is an identifiable entity with specific characteristics and behavior. An object is said to be an A u;
instance of a class. Defining an object is similar to defining a variable of any data type: Space is set
aside for it in memory. Defining objects in this way means creating them. This is also called u.sum();
instantiating them. Once a Class has been declared, we can create objects of that Class by using the getch();
class Name like any other built-in type variable as shown:
return(0);
className objectName
}
Example
Scope Resolution operator
void main( ) {
Member functions can be defined within the class definition or separately using scope resolution
myclass ob1, ob2; //these are object of type myclass operator (::). Defining a member function within the class definition declares the function inline, even
if you do not use the inline specifier. Defining a member function using scope resolution operator uses
// ... program code following declaration
} return-type class-name::func-name(parameter- list) {
cin>>a>>b; return a;
c=a+b; }
cout<<"sum="<<c;
} Another use of scope resolution operator is to allow access to the global version of a variable. In many
situation, it happens that the name of global variable and the name of the local variable are same .In
};
this while accessing the variable, the priority is given to the local variable by the compiler. If we want
to access or use the global variable, then the scope resolution operator (::) is used. The syntax for
accessing a global variable using scope resolution operator is as follows:- Constructor:
A constructor is a special member function whose task is to initialize the objects of its class. It is
:: Global-variable-name
special because its name is same as the class name. The constructor is invoked whenever an object of
its associated class is created. It is called constructor because it construct the value data members of
Static Data Members the class. The constructor functions have some special characteristics.
When you precede a member variable's declaration with static, you are telling the compiler that only
one copy of that variable will exist and that all objects of the class will share that variable. Unlike They should be declared in the public section.
regular data members, individual copies of a static member variable are not made for each object. No
They are invoked automatically when the objects are created.
matter how many objects of a class are created, only one copy of a static data member exists. Thus, all
objects of that class use that same variable. All static variables are initialized to zero before the first They do not have return types, not even void and therefore, they cannot return values.
object is created. When you declare a static data member within a class, you are not defining it. (That
is, you are not allocating storage for it.) Instead, you must provide a global definition for it elsewhere, They cannot be inherited, though a derived class can call the base class constructor.
outside the class. This is done by redeclaring the static variable using the scope resolution operator to Example:
identify the class to which it belongs. This causes storage for the variable to be allocated.
One use of a static member variable is to provide access control to some shared resource used #include< iostream.h>
by all objects of a class. Another interesting use of a static member variable is to keep track of the #include<conio.h>
number of objects of a particular class type that are in existence.
class myclass { // class declaration
Static Member Functions int a;
Member functions may also be declared as static. They may only directly refer to other static
public:
members of the class. Actually, static member functions have limited applications, but one good use
for them is to "preinitialize" private static data before any object is actually created. A static member myclass( ); //default constructor
function can be called using the class name instead of its objects as follows:
void show( );
class name :: function name
};
//Program showing working of static class members
myclass :: myclass( ) {
#include <iostream.h>
cout <<"In constructor\n";
#include<conio.h>
a=10;
class static_type {
}
static int i; //static data member
myclass :: show( ) {
public:
cout<< a;
static void init(int x) {i = x;} //static member function
}
void show() {cout << i;}};
int main( ) {
int static_type :: i; // static data member definition
int ob; // automatic call to constructor
int main(){
ob.show( );
static_type::init(100); //Accessing static function
return0;
static_type x;
}
x.show();
In this simple example the constructor is called when the object is created, and the constructor
return 0; initializes the private variable a to10.
}
Default constructor }
The default constructor for any class is the constructor with no arguments. When no arguments are
Here, obj is a reference to an object that is being used to initialize another object. The keyword const
passed, the constructor will assign the values specifically assigned in the body of the constructor. It is used because obj should not be changed.
can be zero or any other value. The default constructor can be identified by the name of the class
followed by empty parentheses. Above program uses default constructor. If it is not defined explicitly,
then it is automatically defined implicitly by the system.
Destructor
A destructor destroys an object after it is no longer in use. The destructor, like constructor, is a
Parameterized Constructor member function with the same name as the class name. But it will be preceded by the character Tilde
It is possible to pass arguments to constructors. Typically, these arguments help initialize an object (~).A destructor takes no arguments and has no return value. Each class has exactly one destructor. . If
when it is created. To create a parameterized constructor, simply add parameters to it the way you class definition does not explicitly include destructor, then the system automatically creates one by
would to any other function. When you define the constructor's body, use the parameters to initialize default. It will be invoked implicitly by the compiler upon exit from the program to clean up storage
the object. that is no longer accessible.
#include<conio.h> #include<iostream.h>
public: public:
void show() { cout << a << " " << b;} x=10; }
}; ~Myclass(){ //Destructor
} cout<<ob1.x<<” “<<ob2.x;
C++ supports constructor overloading. A constructor is said to be overloaded when the same return 0; }
constructor with different number of argument and types of arguments initializes an object. Output:
10 10
Copy Constructors
The copy constructor is a constructor which creates an object by initializing it with an object of the Destructing……..
same class, which has been created previously. If class definition does not explicitly include copy
Destructing……..
constructor, then the system automatically creates one by default. The copy constructor is used to:
Initialize one object from another of the same type. Friend function
In general, only other members of a class have access to the private members of the class. However, it
Copy an object to pass it as an argument to a function.
is possible to allow a nonmember function access to the private members of a class by declaring it as a
Copy an object to return it from a function. friend of the class. To make a function a friend of a class, you include its prototype in the class
declaration and precede it with the friend keyword. The function is declared with friend keyword. But
The most common form of copy constructor is shown here: while defining friend function, it does not use either keyword friend or :: operator. A function can be a
classname (const classname &obj) { friend of more than one class. Member function of one class can be friend functions of another class.
In such cases they are defined using the scope resolution operator.
// body of constructor
A friend, function has following characteristics. different operations depending on the context. Such operators have to be specifically defined and
appropriate function programmed. When an operator is overloaded, none of its original meaning is
It is not in the scope of the class to which it has been declared as friend. lost. It is simply that a new operation, relative to a specific class, is defined. For example, a class that
A friend function cannot be called using the object of that class. If can be invoked like a defines a linked list might use the + operator to add an object to the list. A class that implements a
normal function without help of any object. stack might use the + to push an object onto the stack.
It cannot access the member variables directly & has to use an object name dot membership An operator function defines the operations that the overloaded operator will perform relative to the
operator with member name. class upon which it will work. An operator function is created using the keyword operator. The
general form of an operator function is
It can be declared either in the public or the private part of a class without affecting its
type classname::operator#(arg-list) { // operations
meaning.
}
Usually, it has the object as arguments.
Program to illustrate use of friend function
Here, the operator that you are overloading is substituted for the #, and type is the type of value
returned by the specified operation. Operator functions can be either members or nonmembers of a
#include<iostream.h> class. Nonmember operator functions are often friend functions of the class.
#include<conio.h> These operators cannot be overloaded:- ., : :, .*, ?
class A{ The process of overloading involves the following steps:
int x, y;
Create a class that defines the data type that is to be used in the overloading operation.
public:
Declare the operator function operator op() in the public part of the class.
friend void display(A &obj);
Define the operator function to implement the required operations.
void getdata() {
cin>>x>>y;
Overloading a unary operator using member function
}
Overloading a unary operator using a member function, the function takes no parameters. Since, there
}; is only one operand, it is this operand that generates the call to the operator function. There is no need
for another parameter.
void display(A &obj){
Overloading unary minus operator
cout<<obj.x<<obj.y;
#include<iostream.h>
}
#include<conio.h>
int main(){
class A {
A a;
int x,y,z;
a.getdata();
public:
display(a);
void getdata(int a,int b,int c) {
getch();
x=a;
return 0;
y=b;
}
z=c;
Operator overloading }
There is another useful methodology in C++ called operator overloading. The language allows not
only functions to be overloaded, but also most of the operators, such as +, -, *, /, etc. As the name void display() {
suggests, here the conventional operators can be programmed to carry out more complex operations. cout<<"\nx="<<x<<"\ny="<<y<<"\nz="<<z;
This overloading concept is fundamentally the same i.e. the same operators can be made to perform
}
{ A t;
z=-z; return t;
} }
}; int main(){
A a; a1.input();
a.getdata(2,3,4); a2.input();
a.display(); getch();
getch(); return 0;
return 0; }
}
this Pointer
Overloading binary operator It is facilitated by another interesting concept of C++ called this pointer. ‘this’ is a C++ keyword.
When a member operator function overloads a binary operator, the function will have only one ‘this’ always refers to an object that has called the member function currently. We can say that ‘this’
parameter. This parameter will receive the object that is on the right side of the operator. The object is a pointer. It points to the object that has called this function this time. While overloading binary
on the left side is the object that generates the call to the operator function and is passed implicitly by operators, we use two objects, one that called the operator function and the other, which is passed to
this pointer. ‘this’ can be used in overloading + operator . the function. We referred to the data member of the calling object, without any prefix. However, the
data member of the other object had a prefix. Always ‘this’ refers to the calling object place of the
#include<iostream.h>
object name.
#include<conio.h>
Inheritance
class A{
Inheritance is the mechanism by which one class can inherit the properties of another. It allows a
int x,y; hierarchy of classes to be build, moving from the most general to the most specific. When one class is
inherited by another, the class that is inherited is called the base class. The inheriting class is called
public:
the derived class. In general, the process of inheritance begins with the definition of a base class. The
void input() { base class defines all qualities that will be common to any derived class. In essence, the base class
represent the most general description of a set of traits. The derived class inherits those general traits
cin>>x>>y;
and adds properties that are specific to that class. When one class inherits another, it uses this general
} form:
void display() { class derived-class-name : access base-class-name{
cout<<"\nx="<<x<<"\ny="<<y<<"\nx+y="<<x+y; // ...
} }
A operator+(A p ); //overload binary + operator
Here access is one of the three keywords: public, private, or protected. The access specifier
}; determines how elements of the base class are inherited by the derived class.
When the access specifier for the inherited base class is public, all public members of the base class d.show2(); //uses derived class’s show2() function
become public members of the derived class. If the access specifier is private, all public members of
getch();
the base class become private members of the derived class. In either case, any private members of the
base class remain private to it and are inaccessible by the derived class. return 0;
It is important to understand that if the access specifier is private, public members of the base }
become private members of the derived class. If the access specifier is not present, it is private by
default. Types of Inheritances
The protected access specifier is equivalent to the private specifier with the sole exception that
Single Inheritance
protected members of a base class are accessible to members of any class derived from that base.
The process in which a derived class inherits traits from only one base class, is called single
Outside the base or derived classes, protected members are not accessible. When a protected member
inheritance. In single inheritance, there is only one base class and one derived class. The derived class
of a base class is inherited as public by the derived class, it becomes a protected member of the
inherits the behavior and attributes of the base class. However the vice versa is not true. The derived
derived class. If the base class is inherited as private, a protected member of the base becomes a
class can add its own properties i.e. data members (variables) and functions. It can extend or use
private member of the derived class. A base class can also be inherited as protected by a derived class.
properties of the base class without any modification to the base class. We declare the base class and
When this is the case, public and protected members of the base class become protected members of
derived class as given below:
the derived class (of course, private members of the base remain private to it and are not accessible by
the derived class). class base_class {
Program to illustrate concept of inheritance };
#include<iostream.h> class derived_ class : visibility-mode base_ class {
#include<conio.h>
};
class base //base class
{
Program to illustrate concept of single inheritance
int x,y;
#include<iostream.h>
public:
#include<conio.h>
void show() {
class base //base class
cout<<"In base class";
{
}
int x,y;
};
public:
class derived : public base //derived class
void show() {
{
cout<<"In base class";
int a,b;
}
public:
};
void show2() {
class derived : public base //derived class
cout<<"\nIn derived class";
{
}
int a,b;
};
public:
int main() {
void show2() {
derived d;
cout<<"\nIn derived class";
d.show(); //uses base class’s show() function
}
};
Hierarchical Inheritance
int main() { The process in which traits of one class can be inherited by more than one class is known as
derived d; Hierarchical inheritance. The base class will include all the features that are common to the derived
classes. A derived class can serve as a base class for lower level classes and so on.
d.show(); //uses base class’s show() function
class base_class2{ Here the base class Base is inherited by both Derived1and Derived2. Derived3 directly inherits both
Derived1and Derived2.However, this implies that Base is actually inherited twice by Derived3.First it
}; is inherited through Derived1, and then again through Derived2.This causes ambiguity when a
class derived_ class : visibility-mode base_ class1 , visibility-mode base_ class2 { member of Base is used by Derived3. Since two copies of Base are included in Derived3, is a
reference to a member of Base referring to the Base inherited indirectly through Derived1or to the
}; Base inherited indirectly through Derived2? To resolve this ambiguity, C++ includes a mechanism by
which only one copy of Base will be included in Derived3. This feature is called a virtual base class.
In situations like this, in which a derived class indirectly inherits the same base class more than once,
Multilevel Inheritance it is possible to prevent multiple copies of the base from being present in the derived class by having
The process in which a derived class inherits traits from another derived class, is called Multilevel that base class inherited as virtual by any derived classes. Doing this prevents two or more copies of
Inheritance. A derived class with multilevel inheritance is declared as : the base from being present in any subsequent derived class that inherits the base class indirectly. The
virtual keyword precedes the base class access specifier when it is inherited by a derived class.
class base_class {
// This program uses a virtual base class.
};
#include <iostream>
class derived_ class1 : visibility-mode base_ class {
using namespace std;
};
class Base {
class derived_ class 2: visibility-mode derived_ class1 {
public:
};
int i;
Here, derived_ class 2 inherits traits from derived_ class 1 which itself inherits from base_class.
};
}; #include<iostream.h>
public: int x, y;
public:
int k;
friend void display(A &obj);
};
friend class B;
// Here Derived3 inherits both Derived1 and Derived2.
void getdata() {
// However, only one copy of base is inherited.
cin>>x>>y;
class Derived3 : publicDerived1, publicDerived2 {
}
public:
};
int product( ) { return i*j*k; }
class B{
};
int p,q;
int main( ) { public:
Derived3 ob; void get(A &obj) {
ob.i = 10; // unambiguous because virtual Base p=obj.x;
ob.j = 3; q=obj.y;
ob.k = 5; }
} cout<<obj.x<<obj.y;
}
If Derived1and Derived2 had not inherited Base as virtual, the statement ob.i=10 would have been
ambiguous and a compile-time error would have resulted. It is important to understand that when a int main(){
base class is inherited as virtual by a derived class, that base class still exists within that derived class.
A a;
For example, assuming the preceding program, this fragment is perfectly valid:
B b;
Derived1 ob;
b.get(a);
ob.i = 100; a.getdata();
display(a);
getch();
Unit-IV a=x;
}
Pointer
int myclass :: get( ) {
A pointer is a variable that contains a memory address. Very often this address is the location of
another object, such as a variable. For example, if x contains the address of y, then x is said to “point return a;
to” y. Pointer variables must be declared as such. The general form of a pointer variable declaration is
}
type *var-name; int main( ) {
Here, type is the pointer’s base type. The base type determines what type of data the pointer will be myclass ob(120); //create object
pointing to. var-name is the name of the pointer variable.
myclass *p; //create pointer to object
To use pointer:
p=&ob; //put address of ob into p
We define a pointer variable.
cout <<"value using object: " <<ob.get( );
Assign the address of a variable to a pointer.
cout <<"\n";
Finally access the value at the address available in the pointer variable. This is done by using cout <<"value using pointer: " <<p->get( );
unary operator * that returns the value of the variable located at the address specified by its
operand. return0;
Example: }
int a=10; //normal variable Notice how the declaration : myclass *p; creates a pointer to an object of myclass. It is
important to understand that creation of an object pointer does not create an object. It creates just a
int*p; //declare pointer pointer to one. The address of ob is put into p by using the statement:
p = &a; // Assign the address of a variable “a” to a pointer “p” p=&ob;
cout<<”a=”<<*p; //prints a=10 Finally, the program shows how the members of an object can be accessed through a pointer.
myclass :: myclass(int x) {
Another point to understand is that although a base pointer can be used to point to a derived object, cout<< "Using derived2's version of func(): ";
the reverse is not true. That is, you cannot access an object of the base type by using a derived class
}
pointer.
};
int main( ) {
C++ Virtual Function base *p;
A virtual function is a member function that is declared within a base class and redefined by a derived
class. In order to make a function virtual, you have to add keyword virtual in front of a function base ob;
definition. When a class containing a virtual function is inherited, the derived class redefines the derived1 d_ob1;
virtual function relative to the derived class. The virtual function within the base class defines the
derived2 d_ob2;
form of the interface to that function. Each redefinition of the virtual function by a derived class
implements its operation as it relates specifically to the derived class. That is, the redefinition creates p = &ob;
a specific method. When a virtual function is redefined by a derived class, the keyword virtual is not
p- >func( ); // use base's func( )
needed. A virtual function can be called just like any member function. However, what makes a
virtual function interesting, and capable of supporting run-time polymorphism, is what happens when p = &d_ob1;
a virtual function is called through a pointer. When a base pointer points to a derived object that
p- >func( ); // use derived1's func( )
contains a virtual function and that virtual function is called through that pointer, C++ determines
which version of that function will be executed based upon the type of object being pointed to by the p = &d_ob2;
pointer. And this determination is made at run time. Therefore, if two or more different classes are
p- >func( ); // use derived2's func( )
derived from a base class that contains a virtual function, then when different objects are pointed to by
a base pointer, different versions of the virtual function are executed. return 0;
#include<iostream.h>
Pure virtual functions
#include<conio.h> Sometimes when a virtual function is declared in the base class, there is no meaningful operation for it
class base { to perform. This situation is common because often a base class does not define a complete class by
itself. Instead, it simply supplies a core set of member functions and variables to which the derived
public: class supplies the remainder. When there is no meaningful action for a base class virtual function to
virtual void func( ) { perform, the implication is that any derived class must override this function. To ensure that this will
occur, C++ supports pure virtual functions. A pure virtual function has no definition relative to the
cout<< "Using base version of func(): "; base class. Only the function prototype is included. To make a pure virtual function, use this general
} form:
class derived1 : public base { The key part of this declaration is the setting of the function equal to 0. This tells the compiler that no
body exists for this function relative to the base class. When a virtual function is made pure, it forces
public: any derived class to override it. If a derived class does not, a compile-time error results. Thus,
voidfunc( ) { making a virtual function pure is a way to guaranty that a derived class will provide its own
redefinition.
cout<< "Using derived1's version of func(): ";
} Abstract class
When a class contains atleast one pure virtual function, it is referred to as an abstract class. Since, an
};
abstract class contains atleast one function for which no body exists, it is, technically, an incomplete
class derived2 : public base { type, and no objects of that class can be created. Thus, abstract classes exist only to be inherited. It is
important to understand, however, that you can still create a pointer to an abstract class, since it is
public:
through the use of base class pointers that run-time polymorphism is achieved. (It is also possible to
voidfunc( ) { have a reference to an abstract class.) .
C++ Streams Cin and Cout objects
The C++ I/O system operates through streams. A stream is logical device that either produces or
consumes information. A stream is linked to a physical device by the C++ I/O system. All streams cout is an object of class ostream. The cout is a predefined object that represents the standard output
behave in the same manner, even if the actual physical devices they are linked to differ. Because all stream in C++. Here, the standard output stream represents monitor. In the language of C++, the <<
streams act the same, the I/O system presents the programmer with a consistent interface. operator is referred to as the insertion operator because it inserts data into a stream. It inserts or sends
Two types of streams: the contents of variable on its right to the object on its left.
Output stream: a stream that takes data from the program and sends (writes) it to destination. For example:
Input stream: a stream that extracts (reads) data from the source and sends it to the program. cout << ``Programming in C++'';
Here << operator is called the stream insertion operator and is used to push data into a stream (in this
case the standard output stream)
cin is an object of class istream. cin is a predefined object that corresponds to the standard input
stream. The standard input stream represents keyboard. The >> operator is called the extraction
operator because it extracts data from a stream. It extracts or takes the value from the keyboard and
assigns it to the variable on it’s right.
For example:
int number;
cin >> number;
C++ provides both the formatted and unformatted IO functions. In formatted or high-level IO, bytes Here >> operator accepts value from keyboard and stores in variable number.
are grouped and converted to types such as int, double, string or user-defined types. In unformatted or
low-level IO, bytes are treated as raw bytes and unconverted. Formatted IO operations are supported Unformatted Input/Output Functions
via overloading the stream insertion (<<) and stream extraction (>>) operators, which presents a
consistent public IO interface. Functions get and put
C++ provides supports for its I/O system in the header file< iostream>. Just as there are different The get function receives one character at a time. There are two prototypes available in C++ for get as
kinds of I/O (for example, input, output, and file access), there are different classes depending on the given below:
type of I/O. The following are the most important stream classes: get (char *)
Class istream :- Defines input streams that can be used to carry out formatted and unformatted input get ()
operations. It contains the overloaded extraction (>>) operator functions. Declares input functions
such get(), getline() and read(). Their usage will be clear from the example below:
Class ostream :- Defines output streams that can be used to write data. Declares output functions put char ch ;
and write().The ostream class contains the overloaded insertion (<<) operator function
cin.get (ch);
In the above, a single character typed on the keyboard will be received and stored in the character
When a C++ program begins, these four streams are automatically opened: variable ch.
Stream Meaning Default Device Let us now implement the get function using the other prototype:
cin Standard input Keyboard char ch ;
cout Standard output Screen ch = cin.get();
cerr Standard error Screen This is the difference in usage of the two prototypes of get functions.
clog Buffer version of cerr Screen The complement of get function for output is the put function of the ostream class. It also has two
forms as given below:
Similarly, the write function displays a line of given size. The prototype of the write function is given setw(int w) Sets the field width to w Output
below:
showbase Turns on showbaseflag Output
write (var, size) ;
showpoint Turns on showpointflag Output
where var is the name of the string and size is an integer.
showpos Turns on showposflag Output
Formatted I/O via manipulators skipws Turns on skipwsflag Input
The C++ I/O system allows you to format I/O operations. For example, you can set a field width,
unitbuf Turns on unitbuf Output
specify a number base, or determine how many digits after the decimal point will be displayed. I/O
manipulators are special I/O format functions that can occur within an I/O statement. uppercase Turns on uppercaseflag Output
Manipulator Purpose Input/Ouput ws Skips leading white space Input
boolalpha Turns on boolaphaflag Input/Output The following program demonstrates several of the I/O manipulators:
endl Outputs a newline character and flushes the stream Output #include<iomanip>
64 • ios::trunc: causes the contents of a pre-existing file by the same name to be destroyed and the file to
be truncated to zero length. When you create an output stream using ofstream, any pre-existing file is
13 automatically truncated.
XXXXXXX144 hi 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
File I/O function open:
A file is a bunch of bytes stored on some storage devices like hard disk, floppy disk etc. File I/O and ofstream myfile;
console I/O are closely related. In fact, the same class hierarchy that supports console I/O also myfile.open ("example.bin", ios::out | ios::app | ios::binary);
supports the file I/O. To perform file I/O, you must include <fstream> in your program. It defines Each of the open member functions of classes ofstream, ifstream and fstream has a default mode that
several classes, including ifstream, ofstream and fstream. In C++, a file is opened by linking it to a is used if the file is opened without a second argument:
stream. There are three types of streams: input, output and input/output. Before you can open a file,
you must first obtain a stream.
Class default mode parameter
To create an input stream, declare an object of type ifstream. ofstream ios::out
To create an output stream, declare an object of type ofstream. ifstream ios::in
fstream ios::in | ios::out
To create an input/output stream, declare an object of type fstream.
For example, this fragment creates one input stream, one output stream and one stream capable of Closing file
both input and output: When we are finished with our input and output operations on a file we shall close it so that the
ifstream in; // input; operating system is notified and its resources become available again. For that, we call the stream's
member function close. This member function takes flushes the associated buffers and closes the
fstream out; // output; file:
fstream io; // input and output myfile.close();
Once you have created a stream, one way to associate it with a file is by using the function open( ). Once this member function is called, the stream object can be re-used to open another file, and the file
This function is a member function of each of the three stream classes. The prototype for each is is available again to be opened by other processes. In case that an object is destroyed while still
shown here: associated with an open file, the destructor automatically calls the member function close.
void ifstream::open(const char*filename,openmode mode=ios::in); To write to a file, you construct a ofsteam object connecting to the output file, and use
void ofstream::open(const char*filename,openmode mode=ios::out | ios::trunc); the ostream functions such as stream insertion <<, put() and write(). Similarly, to read from an
input file, construct an ifstream object connecting to the input file, and use the istream functions
void fstream::open(const char*filename,openmode mode=ios::in | ios::out); such as stream extraction >>, get(), getline() and read().
Here filename is the name of the file, which can include a path specifier. The value of the mode There are two ways of storing data in a file as given below:
determines how the file is opened. It must be a value of type open mode, which is an enumeration
defined by ios that contains the following value: Binary form and Text form
Suppose, we want to store a five digit number say 19876 in the text form, then it will be stored as five
• ios::app: causes all output to that file to be appended to the end. Only with files capable of output.
characters. Each character occupies one byte, which means that we will require five bytes to store
• ios::ate: causes a seek to the end of the file to occur when the file is opened. five-digit integer in the text form. This requires storage of 40 bits. Therefore, if we can store them in
binary form, then we will need only two bytes or 16 bits to store the number. The savings will be
• ios::out: specify that the file is capable of output. much more when we deal with floating point numbers.
• ios::in: specify that the file is capable of input. When we store a number in text form, we convert the number to characters. However, storing a
• ios::binary: causes the file to be opened in binary mode. By default, all files are opened in text number in binary form requires storing it in bits. However, for a character, the binary representation
mode. In text mode, various character translations might take place, such as carriage return/linefeed as well as the text representation are one and the same since, in either case, it occupies eight bits. The
text format is easy to read. We can even use a notepad to read and edit a text file. The portability of
text file is also assured. In case of numbers, binary form is more appropriate. It also occupies lesser 0th position. But, when we say write, then the pointer will advance to one position after the last
space when we store it in binary form and hence it will be faster. The default mode is text. character in the file.
inf.open(“Temp2.txt”); //Reading
Random Access
while(inf){
File pointers inf.getline(buff, 80);
C++ also supports file pointers. A file pointer points to a data element such as character in the file.
The pointers are helpful in lower level operations in files. There are two types of pointers: cout<<buff<<“\n”;
get pointer }
return 0;
The get pointer is also called input pointer. When we open a file for reading, we can use the get
pointer. The put pointer is also called output pointer. When we open a file for writing, we can use put }
pointer. These pointers are helpful in navigation through a file. When we open a file for reading, the
get pointer will be at location zero and not 1. The bytes in the file are numbered from zero. Therefore,
automatically when we assign an object to ifstream and then initialize the object with a file name, the
get pointer will be ready to read the contents from 0th position. Similarly, when we want to write we
will assign to an ofstream object a filename. Then, the put pointer will point to the 0th position of the
given file name after it is created. When we open a file for appending, the put pointer will point to the