You are on page 1of 78

PROGRAMMING IN C++

Introduction of C++:
 C++ is one of the world's most popular programming languages.
 C++ is an extension to the C language.
 C++ also called as “C with Classes “.super-set of C language.
 C++ is a Objected Oriented Programming language and facilitates design, resuse and
maintenance for complex software.

C++ Features
The C++ (also read as C plus plus) is a general-purpose object oriented programming language. C++
is an enhanced version of the C language introduced with many new features
 Simple :- 
C++ comes with easy to learn simple English language like syntax, which makes it very easy to
understand and develop C++ Programs.

 High Performance :- 


Being a statically typed language, C++ is generally performs more than any dynamically
typed languages because the code is type-checked before it is executed.

 Statically Typed :-
This allows compiler to catch the bugs before executing the program.
 Multi Paradigm :- 
C++ is a multi-paradigm object oriented programming language that supports procedural,
object-oriented (OOPs), and generic programming whereas C is a procedural programming
language.
 Object Oriented :- 
C++ is a general-purpose, multi-paradigm object oriented programming language that
supports procedural, object-oriented (OOPs), and generic programming whereas C is a
procedural programming language. It compliance with four of the major OOPs principles
Inheritance, Polymorphism, Encapsulation and Abstraction.
 Standard Template Library(STL) :-
 C++ comes with rich inbuilt function library through Standard Template Library (STL).

 Pointers :- 
C++ supports the use of pointers which are often not available in several programming
languages.
 Portable :-
 C++ is Portable language, which allows you writing a program irrespective of operating
system as well as Hardware. Programs written in C++ can be executed in many machines with
little bit or no change.
C++ is a highly portable language that supports multi-device, multi-platform application
development.
 Reusable :-
C++ comes with an increased level of code re-usability due to the object oriented programming
model and libraries.
 Exception handling :- C++ supports exception handling which was not possible in C.

 Memory Management :- 


 C++ supports the dynamic memory allocation, which gives user complete control over memory
management. In C++ language, we can allocated and free up memory dynamically at any time.

CHANDRA MOULI (DEPT OF CS in KU) Page 1


9640235390
PROGRAMMING IN C++

 Case Sensitive :- C++ is a case sensitive programming language. In C++ programming “abc”
and “ABC” both are different.

 Compiled :- C++ is compiled language, which means C++ source code need to be first compiled
into low-level code and then it can be executed, unlike interpreted programming languages where
compilation is not needed.

 Platform Dependent :- C++ is a platform dependent language. A language is said to be platform


dependent whenever the program is execute in the same operating system where that was
developed and compiled but not run and execute on other operating system.

History of C++:
 C++ was developed by Bjarne Stroustrup  in 1979 at Bell Labs.
 It was the first language to support the OOPS concepts.
 First it called as “C with Classes “.
 In 1983, the name was changed to C++ .Here ++ refers to adding new features (inheritance,
pholymarphizam, classes, objects) to the C languages.
Application of C++ :

1. Operating Systems
Microsoft Windows or Mac OSX or Linux - all of them are programmed in C++. C/C++ is
the backbone of all the well-known operating systems

2. Browsers
 Web browsers ( Google chrome,Mozilla Firefox.IE) are programmed in C++.
 Faster execution to make sure that users don’t have to wait for the content to come
up on the screen.

3. Libraries
 Many high-level libraries use C++ as the core programming language.
 One of the most widely used Machine Learning libraries uses C++ as the
backend programming language. Such libraries required high-performance
computations. As a result, performance becomes critical.
 C++ comes to the rescue in such libraries.

4. Graphics
 All graphics applications require fast rendering
 . Software that employ computer vision, digital image processing, high-end
graphical processing - they all use C++ as the backend programming language.
 Even the popular games that are heavy on graphics use C++ as the primary
programming language.
 The speed that C++ offers in such situations helps the developers in expanding the
target audience because an optimized application can run even on low-end
devices that do not have high computation power available.

5. Banking Applications
 One of the most popularly used core-banking system - Infosys Finacle uses C++ as one
of the backend programming languages.

CHANDRA MOULI (DEPT OF CS in KU) Page 2


9640235390
PROGRAMMING IN C++

 Banking applications process millions of transactions on a daily basis and require high
concurrency.

 C++ automatically becomes the preferred choice in such applications owing to its
speed and multithreading support that is made available through various Standard
Template Libraries that come as a part of the C++ programming kit.

6. Cloud/Distributed Systems
 Large organizations that develop cloud storage systems and other distributed systems
also use C++ because it connects very well with the hardware and is compatible with a
lot of machines.
 Cloud storage systems use scalable file-systems that work close to the hardware.
 C++ becomes a preferred choice in such situations because it is close to the hardware
and also the multithreading libraries in C++ provide high concurrency and load
tolerance which is very much needed in such scenarios.

7.Databases
 Postgres and MySQL - two of the most widely used databases are written in C++ and C, the
precursor to C++.
 These databases are used in almost all of the well-known applications that we all use in our day
to day life - Quora, YouTube, etc.

8. Embedded Systems
Various embedded systems like medical machines, smart watches, etc. use C++ as the primary
programming language because of the fact that C++ is closer to the hardware level as compared to other
high-level programming languages.

9. Telephone Switches
Because of the fact that it is one of the fastest programming languages, C++ is widely used in
programming telephone switches, routers, and space probes.

10. Compilers
The compilers of various programming languages use C and C++ as the backend programming language.

CHANDRA MOULI (DEPT OF CS in KU) Page 3


9640235390
PROGRAMMING IN C++

Example Programs C++:

Without class C++ program:


/* Write a C++ program to display welcome to c++ */
#include <iostream.h>
#include <conio.h>
void main ()
{
cout<<”welcome to c++”;
}

OUTPUT: welcome to c++”;


With class C++ program:

/* Write a c++ program to display Employee details */


#include <iostream.h>
#include <conio.h>
class Employee
{ int eno;
string name;
long salary;
public :
void getdata()
{
cout<<”enter employee no”<<endl;
cin>>eno;
cout<<”enter employee name”<<endl;

CHANDRA MOULI (DEPT OF CS in KU) Page 4


9640235390
PROGRAMMING IN C++

cin>>name;
cout<<”enter employee salary”<<endl;
cin>>salary;
}

void putdata()
{
cout<<” employee no”<< eno <<endl;
cout<<” employee name”<< name <<endl;
cout<<”enter employee salary”<< salary <<endl;
}
};
void main ()
{
clrscr();
Employee e;
e.getdata();
e.putdata();
getch();
}

Output :
enter employee no 101
enter employee name RAJU
enter employee salary 20,000
employee no 101
employee name RAJU
employee salary 20,000

C++ TOKENS
A token is the smallest element of a program that is
meaningful to the compiler.
Tokens can be classified as follows:  
 Keywords
 Identifiers
 Constants
 Strings
 Special Symbols
 Operators

1.Keywords: 
Keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program.
 C language supports 32 keywords which are given below: 
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned

CHANDRA MOULI (DEPT OF CS in KU) Page 5


9640235390
PROGRAMMING IN C++

continue for signed void


default goto sizeof volatile
do if static while
While in C++ there are 31 additional keywords other than C Keywords they are: 
asm bool catch class
const_cast delete dynamic_cast explicit
export false friend inline
mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw
true try typeid typename
using virtual wchar_t

2.Identifiers:
 Identifiers are used as the general terminology for the naming of variables, functions and
arrays.

 These are user-defined names consisting of an arbitrarily long sequence of letters and digits
with either a letter or the underscore(_) as a first character.

 Identifier names must differ in spelling and case from any keywords.
 You cannot use keywords as identifiers;
they are reserved for special use. Once declared, you can use the identifier in later program statements
to refer to the associated value.
A special kind of identifier, called a statement label, can be used in goto statements. 
There are certain rules that should be followed while naming c identifiers: 
 
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.
 main: method name.
 a: variable name.

3.Constants: Constants are also like normal variables. But, the only difference is, their values can
not be modified by the program once they are defined. Constants refer to fixed values. They are also
called literals. 
Constants may belong to any of the data type

Syntax:
const data_type variable_name; (or) const data_type *variable_name; 
Types of Constants: 
 
 Integer constants – Example: 0, 1, 1218, 12482
 Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
 Octal & Hexadecimal constants – Example: octal: (013 ) 8 = (11)10, Hexadecimal: (013)16 =
(19)10
 Character constants -Example: ‘a’, ‘A’, ‘z’
 String constants -Example: “GeeksforGeeks”

CHANDRA MOULI (DEPT OF CS in KU) Page 6


9640235390
PROGRAMMING IN C++

4.Strings: Strings are nothing but an array of characters ended with a null character (‘\0’). This null
character indicates the end of the string. Strings are always enclosed in double-quotes. Whereas, a
character is enclosed in single quotes in C and C++.Declarations for String: 
 
 char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
 char string[20] = “geeksforgeeks”;
 char string [] = “geeksforgeeks”;
 when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the
string value.
 When we declare char as “string[]”, memory space will be allocated as per the requirement
during the execution of the program.
 5.Special Symbols: The following special symbols are used in C having some special meaning
and thus, cannot be used for some other purpose.[] () {}, ; * = # 
 
 Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and function
parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
 Comma (, ): It is used to separate more than one statements like for separating parameters in
function calls.
 Colon(:): It is an operator that essentially invokes something called an initialization list.
 Semicolon(;): It is known as a statement terminator.  It indicates the end of one logical entity.
That’s why each individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable.
 Assignment operator(=): It is used to assign values.
 Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
 6.Operators: Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act upon are called operands. 
Depending on the number of operands that an operator can act upon, operators can be classified
as follows: 
 
 Unary Operators: Those operators that require only a single operand to act upon are known as
unary operators.For Example increment and decrement operators
 Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators are classified into : 
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operator

OOPs Concepts
Object-Oriented Programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object

CHANDRA MOULI (DEPT OF CS in KU) Page 7


9640235390
PROGRAMMING IN C++

2. Class
3. Inheritance
4. Polymorphism
5. Data Abstraction & Encapsulation
6. Message communication
7. Dynamic binding

OBJECTS & CLASSES


Objects are the basic runtime entities in object orientedsystem. They may represent a place, person or any
item that the program may handle.
- An entity that has state and behavior is known as an object
E.g. chair, bike, marker, pen, table, car etc.

An object has three characteristics:


 State: represents data (value) of an object.
 Behavior: represents the behavior (functionality) of an object
 Identity: Object identity is typically implemented via a unique ID.

Class: Collection of Objects of same type is known as class


Ex: mango, apple and orange are the members of the class fruit

Data Abstraction: Hiding the implementation details of a particular object is known as Data abstraction

Data Encapsulation: Combining all the functions together is known as Data Encapsulation.
- The wrapping of data and methods into a single unit is called encapsulation which is one of the
important features of class. The data is not accessible to the outside world and only those methods which
are wrapped in the class can access it which is known as data hiding.

Polymorphism: means the ability to take more than one form.

Inheritance: It is the process by which the objects of one class acquire the properties of objects of
another class.
- Extending the parent class properties to child class is the concept of Inheritance.
-It provides the idea of reusability which means that we can additional features to an existing class
without modifying it which is possible by deriving a new class from the existing one where the new class
will have the combined features of both the classes.

Dynamic binding
Means that the code associated with given procedure call is not known until the time of the call at
runtime. It is associated with polymorphism and inheritance.

Message Communication
Objects communicate with each other by sending and receiving information as people.

It involves specifying the name of the object, method name and information to be sent.

example:
Employee. salary (ename);

CHANDRA MOULI (DEPT OF CS in KU) Page 8


9640235390
PROGRAMMING IN C++

Depending on the above principles, they support,


- Object based programming language
-Object oriented programming language

Object based programming language supports


- Data encapsulation
- Data hiding & access mechanisms
- Automaticinitialization& clear up of objects
- Operator overloading
Ex: smalltalk

- Object oriented programming language


Object based programming language + dynamic binding+inheritance
Ex: C++, JAVA

Programming approaches
1. Top to down approach -C
2. Bottom to top approach - C++

Working with C++


- Load windows o/s
- Chose start->search programs->type command
- At the dos prompt, type cd\
- Then type, cd tc\bin
- Type tc
Creating the source file (user understandable program created using high level language)
1. C++ programs can be created using any text editor
2. save the program file -> save (or) press function key F2
Turbo C++ and Borland C++ uses .cpp as file extension
3. Compiling & linking - ctrl + f9
4. Press function key, alt+F5 to see the result

The iostream.h file (input/output stream)


#include <iostream.h>
This directive causes the preprocessor to add the contents of iostream.h file to the program. It contains
the declarations for the identifier cin and the operator >> and cout and the operator <<.
Comments
Are non executable statements which are used for user identification?

It supports single-line (//) and multi-line (/* ==== */) comments.


Note: characters available inside any comment are ignored by compiler.

Output Operator
The statement
cout<<”welcome to C++ programming”;

causes the string in quotation marks to be displayed on the screen. The identifier cout (pronounced as ‘C
out’) is a predefined object that represents the standard output stream(ostream)in C++.
The operator << is called the insertion or put to operator which inserts or sends the contents of the
variable on its right to the object on its left.

CHANDRA MOULI (DEPT OF CS in KU) Page 9


9640235390
PROGRAMMING IN C++

Screen
^
|
Cout------------------ <<---------------------------------C++
Object insertion operator variable

Return Statement
main() returns integer type to operating system. Therefore every main() in C++ should end with
return(0) statement otherwise a warning may occur.(function should return a value)

Input operator
int number1;
cin>>number1;
Is an input statement & causes the program to wait for the user to type in a number which is
placed in the variable number1. The identifier cin (pronounced as “C in”) is a predefined object in C++
that corresponds to the standard input stream which is keyboard.

The operator >> is known as extraction or get from operator which extracts or takes the value
from the keyboard and assigns it to the variable on its right.
Cin--------------->>---------------------------------------12.5
Object extraction operator variable
^
|
Keyboard
Cascading of I/O Operators
The multiple use of << and >> in one statement is known as cascading.

Example:
cout<<”sum = “<<sum;
cin>>a>>b;
o/p:
sum=10

Basic Syntax:

Case Sensitivity–C++ is case sensitive, which means identifier Hello and hello would have different
meaning in C++.
ASCII (American standard code for information interchange) Characters
A to Z - 65 to 90 (+- 32)
a to z - 97 to 122
0 to 9 - 48 to 56
Identifiers &keywords
All C++ components require names. Names used for variables, functions etc are called identifiers.

In C++, there are several points to remember about identifiers. They are as follows

1. All identifiers should begin with a letter (A to Z or a to z)


Ex: stud_name
2. After the first character, identifiers can have any combination of characters.

CHANDRA MOULI (DEPT OF CS in KU) Page 10


9640235390
PROGRAMMING IN C++

Ex: stud_name1
3. A key word cannot be used as an identifier.
4. Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.

C++ Keywords (32+16=48)

The following list shows the reserved words in C++. These reserved words may not be used as constant
or variable or any other identifier names.

asm double new switch


auto else operator template
break enum private this
case extern protected throw
catch float public try
char for register typedef
class friend return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while

Data Types – determines what type of data a variable holds


1. Built in/ primitive/primary/fundamental data types
. integral type – int,char
. floating type – float,double
. void
2. User defined data types
. struct(structure)
. union
. class
.typedef(type definition)
.enum(ennumeration)
3. Derived type
. array
. pointer
. function

Declaration of variables & constants

Variable : It is a data item that stores data value that changes(varies) during program execution.
Syntax:
datatype variable(s);
ex:
int a;
int b,c;

CHANDRA MOULI (DEPT OF CS in KU) Page 11


9640235390
PROGRAMMING IN C++

or
int a,b,c;
char x;
float y;
double z;

constants : refers to fixed value whose value does not change during program execution.
- Constants are declared using the keyword const
Ex:
Const float pi=3.14;

2) enum{var1,var2,….};
Enum stands for enumeration
Ex:
enum{a,b,c};
declares a,b and c as set of integer constants with the values assigned 0,1,2;

which is equivalent to
const int a=0,b=1,c=2;

enum{a,b,c=10};
a=0,b=1,c=10
enum{a,b=5,c};
a=0,b=5,c=6

Reference variables
It provides an alias or alternate name for previously defined variable.

Syntax:
datatype & referencename=variable name;

Example:
float total=200;
float&sum=total; //reference variable
cout<<total;o/p 200
cout<<sum;o/p 200

Operators
It is symbol to perform an operation.
- Arithmetic operators +-*/%
- Relational operators <>>= <= <> ==
- Logical “ && || !
- Assignment “ =
- Bit wise “
- Increment & decrement “ ++ --
- Special operators , & *
- Conditional operators ? :
CHANDRA MOULI (DEPT OF CS in KU) Page 12
9640235390
PROGRAMMING IN C++

- size of “
C++ Operators
<< insertion operator
>> extraction operator
:: scope resolution operator
::* pointer-to member declarator
->* pointer to member operator
.* pointer to member operator
Delete memory release operator - memory management operators
new memoryallocation operator
endl line feed operator - manipulators
setw field width operator
:: scope resolution operator
It allows access to global version of a variable and also used to specify to which class that
function belongs to.

//scope.cpp
//program to demonstrate scope resolution operator ::
#include<iostream.h>
#include<conio.h>

int a=5; //global variable


void main()
{
int a=10; //local variable
clrscr();
cout<<"value of a (local)="<<a<<endl;
cout<<"value of a(global)="<<::a<<endl;
}

Control structures – are used to control the flow of data


Types of control structures
1. sequential statements
2. selection statements
3. iterative statements

sequential statements – are the statements which are executed in a sequential manner. These are by
default.

Selection statements – are those statements which are executed basing on certain condition (selection).
Ex: decision making statements(if construct,switch construct)

Iterative statements – are those statements which are executed repeated number of times as long as
condition is true or until condition becomes false.
Ex:do loop, for loop, while loop

Functions

CHANDRA MOULI (DEPT OF CS in KU) Page 13


9640235390
PROGRAMMING IN C++

Function is a sub program which contains self contained block of statements.


Function is a generalized routine to perform step by step instructions under single name.
It provides modular programming i.e. dividing a program into2 pieces i.e. calling/main program or
called/sub program.

Advantages
- Readability
- Reusability

Types of functions
1. Built in / predefined functions/library functions – are those functions which are ready made
available
2. User defined functions (UDF’s) – are those functions which are defined by the user as per his
requirement.

Built in / predefined/library functions


- Character functions
- Mathematical functions
- String functions
- Memory management functions

Categories of User defined functions (UDF’s)


1. Function with no argument & no return value
2. Function with no argument & return value
3. Function with argument & no return value
4. Function with argument & return value

Argument – is a parameter passed from main program to a sub program.

Types of arguments
1. Actual arguments – are those arguments which are passed from main to sub program.
2. Formal arguments – are those arguments which are declared in sub program to receive the formal
arguments sent from main program matching the order, number and type of arguments.

Void func(int,int); //function prototyping


Main()
{
Int a,b;
Func(a,b); // aa
}

Func(int x,int y) //fa


{
====
}

Function prototyping
It describes the function interface to the compiler by giving details like number & type of
arguments and type of return values.
CHANDRA MOULI (DEPT OF CS in KU) Page 14
9640235390
PROGRAMMING IN C++

Syntax:
Type functionname (argument-list);
Note: argument list contains the type and names of arguments that must be passed to the function.
Void func(int,int); //function prototyping
Main()
{
Int a,b;
Func(a,b); // aa
}

Void Func(int x,int y) //fa


{
====
}

Invoking/Calling a function
A function can be called in3 ways
. Call/Pass by value
. Call by address (pointers)
. Call by reference

Call by value
When a function is called by value, copy of values passed by actual arguments is received by
formal arguments on one to one basis matching the order, data type & size.
Any changes made to the formal argument values that do not reflect the actual argument values
since their address differ.
Ex: callbyval.cpp
//demonstration of call by value
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>

//function prototyping
void func(int);
//main or calling program
main()
{
int a;
clrscr();
cout<<"enter value for a"<<endl;
cin>>a;
cout<<"value of a before function call is : "<<a<<endl;
//calling function with argument & no return value
func(a);
cout<<"value of a after function call is : "<<a<<endl;

CHANDRA MOULI (DEPT OF CS in KU) Page 15


9640235390
PROGRAMMING IN C++

return(0);
}

//called or sub program


void func(int x)
{
x++;
cout<<"value of x is :"<<x<<endl;
}

Call by Address (Pointers)


- When a function is called by address, receiving argument should be a pointer of that type.
- Any changes made to the formal argument values reflect the actual argument values since formal
argument is a pointer pointing to actual argument address.
Ex:callbyad.cpp
//demonstration of call by address
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>

//function prototyping
void func(int*);
//main or calling program
main()
{
int a;
clrscr();
cout<<"enter value for a"<<endl;
cin>>a;
cout<<"value of a before function call is : "<<a<<endl;
//calling function with argument & no return value
//call by address
func(&a);
cout<<"value of a after function call is : "<<a<<endl;
return(0);
}

//called or sub program


void func(int *x)

{
(*x)++;
cout<<"value of x is :"<<*x<<endl;
}

Call by Reference

CHANDRA MOULI (DEPT OF CS in KU) Page 16


9640235390
PROGRAMMING IN C++

Provision of reference variables in C++ permits us to pass parameters to the functions by


reference. 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 own arguments, it is actually working on the original data.

//callbyrf.cpp
//demonstration of call by reference
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>

//function prototyping
void func(int&);
//main or calling program
main()
{
int a;
clrscr();
cout<<"enter value for a"<<endl;
cin>>a;
cout<<"value of a before function call is : "<<a<<endl;
//calling function with argument & no return value
//call by reference
func(a);
cout<<"value of a after function call is : "<<a<<endl;
return(0);
}

//called or sub program


void func(int &x)
{
x++;
cout<<"value of x is :"<<x<<endl;
}

Functions with default arguments


In C language,
1) Number of actual arguments = number of formal arguments matching the order, data type and size
2) If Number of actual arguments > number of formal arguments then extra actual arguments are
ignored.
3) If Number of actual arguments < number of formal arguments then extra formal arguments are
filled with garbage (unknown) value.

The above problem can be solved in C++ using Functions with default arguments.

C++ allows to call a function without specifying all its arguments. In such cases, the function
assigns a default value to the parameter which does not have matching argument in the function call.

CHANDRA MOULI (DEPT OF CS in KU) Page 17


9640235390
PROGRAMMING IN C++

Default arguments are specified when the function is declared. The compiler looks at the
prototype to see how many arguments a function uses and alters the program for possible default values.
Note:
1. A default argument is checked for type at the time of declaration and evaluated at the time of call.
2. Only the trailing arguments can have default values i.e. from right to left.
3. Default value cannot be provided to a particular argument in the middle of an argument list.

//defaarg.cpp
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//function with default arguments
//function prototypedeclaration
void func (int p, int q, int r=35);

void main()
{
int a, b;
clrscr ();
cout<<"enter value for a and b"<<endl;
cin>>a>>b ;
func(a,b); // one argument missing
}

//sub program
void func(int x,int y,int z)
{
int d;
cout<<"value of x is :"<<x<<endl;
cout<<"value of y is :"<<y<<endl;
cout<<"value of z is :"<<z<

Function Overloading
It is the usage of same function name to create functions that perform a variety of different tasks.
This is known as function polymorphism/function overloading in OOPS.
-The function would perform different operations depending on the argument list in the function call and
the correct function to be invoked is determined by checking the number & type of the arguments but
not on the function type.

Example 1:
//demonstration of function overloading
//addition of 2 character, 2 integers & 2 floating values
//funcover.cpp
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>

//function prototyping
char add(char,char);
int add(int,int);

CHANDRA MOULI (DEPT OF CS in KU) Page 18


9640235390
PROGRAMMING IN C++

float add(float,float);

//main or calling program


main()
{
char a,b,p;
int c,d,q;
float e,f,r;
clrscr();
cout<<"enter any 2 character values"<<endl;
cin>>a>>b;
cout<<"enter any 2 integer values"<<endl;
cin>>c>>d;
cout<<"enter any 2 floating value"<<endl;
cin>>e>>f;

//calling a function
//call by value
p=add(a,b);
q=add(c,d);
r=add(e,f);
cout<<"addition of"<<a<<" + "<<b<<" is :"<<p<<endl;
cout<<"addition of"<<c<<" + "<<d<<" is :"<<q<<endl;
cout<<"addition of"<<e<<" + "<<f<<" is :"<<r<<endl;
return(0);
}

//called or sub program


//characters addition
char add(char x,char y)
{
return(x+y);
}

//integer addition
int add(int m,int n)
{
return(m+n);
}

//floating addition
float add(float r,float s)
{
return(r+s);
}

Example 2:

CHANDRA MOULI (DEPT OF CS in KU) Page 19


9640235390
PROGRAMMING IN C++

//funover1.cpp
//function overloading
//drawing lines in different designs

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>

//function prototyping
void line(void);
void line(char);
void line(int);
void line(char,int);
//main or calling program
main()
{
clrscr();
//calling a function
//call by value
line();
line('*');
line(70);
line('=',80);
return(0);
}

//called or sub program


//characters addition
void line(void)
{
for(int i=1;i<=50;i++)
{
cout<<"-";
}
cout<<endl;
}

void line(char x)
{
for(int i=1;i<=60;i++)
{
cout<<x;
}
cout<<endl;
}

void line(int m)
{
for(int i=1;i<=m;i++)

CHANDRA MOULI (DEPT OF CS in KU) Page 20


9640235390
PROGRAMMING IN C++

{
cout<<"+";
}
cout<<endl;
}

void line(char p,int n)


{
for(int i=1;i<=n;i++)
{
cout<<p;
}
cout<<endl;
}

Classes & Objects

A class is collection of objects of similar type which is an extension of the idea of structure of C.
Class has 2 parts namely
- Class declaration – describes the type & scope of its members
- Class function definitions – describes how the class functions are implemented.

Declaration of class

class <classname>
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};

The keywords private & public are known as visibility labels.

private
Members that have been declared as private can be accessed only form within the class. If nothing is
specified, by default it is private.

public
public members can be accessed from outside the class too.

Note:
Variables declared inside the class are known as data members and functions are known as member
functions or methods

Objects

CHANDRA MOULI (DEPT OF CS in KU) Page 21


9640235390
PROGRAMMING IN C++

Objects are instance of class & this process is known as instantiation.


Once a class is created, any number of objects of that class can be created.

Syntax:
Classname object(s);
Example:
class fruit
{
int a;
======
};

void main()
{
fruit mango,banana; //class type variables ie objects
}

mango.a=10;
mango.getdata();

Defining member functions


Member functions can be defined
- Inside the class definition
- Outside class definition

//insclass.cpp
//inside class definition
//defining member function inside the class definition
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class student // name of class


{
private:
//data members
int rno;
char name[16];
public:
//member function definitions inside class
void getdata(void)
{
cout<<"enter value for roll number & name of student"<<endl;
cin>>rno>>name;
}

CHANDRA MOULI (DEPT OF CS in KU) Page 22


9640235390
PROGRAMMING IN C++

void putdata(void)
{
cout<<"roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}
}; //end of class

void main()
{
student s; //object
clrscr();
//invoking member functions of object
s.getdata();
s.putdata();
}

Defining a member function outside the class


Member functions that are declared inside a class have to be defined separately outside the class.
An important difference between a member function & normal function is that a member
function incorporates a membership “identity label” in the header which tells the compiler to which class
the function belongs to.

Syntax:
return-type classname : : functionname(argument declaration)
{
function body;
}

NOTE:
- The membership label class-name:: tells the compiler that the function function-name belongs to
the class class-name. That is, the scope of the function is restricted to the class name specified in the
header line.
- The symbol:: is called scope resolution operator.

//outclass.cpp
//defining member function outside the class
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class student
{
//private data members
int rno;
char name[16];
public:
void getdata(void); //prototype declarations
void putdata(void);
};

CHANDRA MOULI (DEPT OF CS in KU) Page 23


9640235390
PROGRAMMING IN C++

//member function definition outside the class


void student :: getdata(void)
{
cout<<"enter roll number & name of student"<<endl;
cin>>rno>>name;
}

void student :: putdata(void)


{
cout<<"roll number is :"<<rno<<endl;
cout<<"name is :"<<name<<endl;
}

void main()
{
student s; //object creation
clrscr();
//invoking member functions on object
s.getdata();
s.putdata();
}

Nesting of member functions


A member function can be called by using its name inside another member function of the same
class. This is known as nesting of member functions.

//nestfunc.cpp
//nesting of member functions
//finding largest of 2 numbers
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class big
{
//private data members
int a,b;
public:
void getdata(void); //prototype declarations
void putdata(void);
int biggest(void);
};

//member function definition outside the class


void big :: getdata(void)
{
cout<<"enter values for a and b"<<endl;
cin>>a>>b;
}

CHANDRA MOULI (DEPT OF CS in KU) Page 24


9640235390
PROGRAMMING IN C++

void big :: putdata(void)


{
cout<<"value of a = "<<a<<endl;
cout<<"value of b = "<<b<<endl;
cout<<"biggest value = "<<biggest()<<endl; //nesting of function
}

int big :: biggest(void)


{
if(a>b)
return a;
else
return b;
}

void main()
{
big b; //object creation
clrscr();
//invoking member functions on object
b.getdata();
b.putdata();
}

Objects as function arguments


Like any other datatype, an object may be used as function argument which can be done in 2
ways.
. A copy of the entire object is passed to the function (call by value)
. Only the address of the object is transferred to the function (call by reference)

Int a,x;
Char b,y;
Float c,z;

X=Fun1(a);
Y=Fun2(b);
Z=Fun3(c);

//addtime.cpp
//addition of 2 times without any return value
//function with object as argument without return value
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class time
{
//private data members

CHANDRA MOULI (DEPT OF CS in KU) Page 25


9640235390
PROGRAMMING IN C++

int hours,minutes;
public:
//getting time
void gettime(int h,int m)
{
hours=h;
minutes=m;
}
//displaying time
void puttime(void)
{
cout<<" hours = "<<hours<<" and minutes ="<<minutes<<endl;
}

//addition of 2 times
void sum(time tt1,time tt2)
{
minutes=tt1.minutes+tt2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+tt1.hours+tt2.hours;
}
};

void main()
{
time t1,t2,t3;
clrscr();
t1.gettime(3,45); //get time1
t2.gettime(4,55); //get time2
//addition of 2 times
t3.sum(t1,t2); //calling sum function with object as function argument
//t3=t1+t2;
cout<<"time 1 ="<<endl;
t1.puttime();
cout<<"time t2="<<endl;
t2.puttime();
cout<<"time 3="<<endl;
t3.puttime();
}

Object as return value

Like any other type, it is possible to return object type value.

//addtimer.cpp
//addition of 2 times
//function with object as argument and with return value

CHANDRA MOULI (DEPT OF CS in KU) Page 26


9640235390
PROGRAMMING IN C++

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class time
{
//private data members
int hours,minutes;
public:
//getting time
void gettime(int h,int m)
{
hours=h;
minutes=m;
}
//displaying time
void puttime(void)
{
cout<<" hours = "<<hours<<" and minutes ="<<minutes<<endl;
}

//addition of 2 times
time sum(time tt2)
{
time t;
t.minutes=minutes+tt2.minutes;
t.hours=t.minutes/60;
t.minutes=t.minutes%60;
t.hours=t.hours+hours+tt2.hours;
return t;
}
};

void main()
{
time t1,t2,t3;
clrscr();
t1.gettime(3,45); //get time1 //explicit function call
t2.gettime(4,55); //get time2
//addition of 2 times
t3=sum(t2); //calling sum function with object as function argument
//t3=t1+t2;
cout<<"time t1 ="<<endl;
t1.puttime(); //explicit function call
cout<<"time t2="<<endl;
t2.puttime();
cout<<"time 3="<<endl;
t3.puttime();
}

CHANDRA MOULI (DEPT OF CS in KU) Page 27


9640235390
PROGRAMMING IN C++

Constructors & Destructors

Constructor
A constructor is a “special” member function whose task is to initialize the objects of its class.
The constructor is invoked whenever an object of its associated class is created.
- It is so called because it constructs the values of the data members of the class.
-
Syntax:
class <classname>
{
private:

Public:
//constructor function definition
classname()
{
Function body;
}
};

Characteristics of Constructor
1. Function name should have same name as that of class name
2. Should be declared in the public section
3. Invoked automatically whenever object is created
4. They do not have return types
5. They cannot be inherited thru a derived class but can call the base class
Constructor
6. They can have default arguments

Types of constructors
1. Default constructor
2. Parameterized constructor
3. Copy constructor
Default constructor
A constructor that accepts no parameters is called default constructor.

//class with default constructor


#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class defcons //classname
{
//private data members
int a,b,c;
public:
//default constructor definition
defcons(void)
{

CHANDRA MOULI (DEPT OF CS in KU) Page 28


9640235390
PROGRAMMING IN C++

a=5; //giving initial values to data members a and b


b=10;
}
void display(void)
{
cout<<" value of a ="<<a<<endl;
cout<<" value of b ="<<b<<endl;
c=a+b;
cout<<"sum is "<<c<<endl;
}
};

void main()
{
defcons def; //default constructor
clrscr();
def.display(); //explicitly invoking a function on object
}

Parameterised constructor
Constructor that takes arguments is called parameterized constructor.

//class with parameterised constructor


#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class paracons //classname
{
//private data members
int a,b,c;
public:
//default constructor definition
paracons(int x,int y)
{
a=x;
b=y;
}
void display(void)
{
cout<<" value of a ="<<a<<endl;
cout<<" value of b ="<<b<<endl;
c=a+b;
cout<<"sum is "<<c<<endl;
}
};

CHANDRA MOULI (DEPT OF CS in KU) Page 29


9640235390
PROGRAMMING IN C++

void main()
{
paracons para(5,10); //parameterised constructor
clrscr();
para.display(); //explicitly invoking a function on object
}

//dfcontme.cpp
//addition of 2 times
//function with object as argument and with return value
//class with default &parameterized constructor
// Working with multiple constructors
//constructor overloading

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//time sum(time);
class time
{
//private data members
int hours,minutes;
public:
//default constructor definition
time()
{
hours=0;
minutes=0;
}
//parameterised constructor definition
time(int hrs,int mins)
{
hours=hrs;
minutes=mins;
}
//displaying time
void puttime(void)
{
cout<<" hours = "<<hours<<" and minutes ="<<minutes<<endl;
}

//addition of 2 times
time sum(time tt2)
{
time t;
t.minutes=minutes+tt2.minutes;
t.hours=t.minutes/60;
t.minutes=t.minutes%60;
t.hours=t.hours+hours+tt2.hours;

CHANDRA MOULI (DEPT OF CS in KU) Page 30


9640235390
PROGRAMMING IN C++

return t;
}
};

void main()
{
time t1(3,45),t2(4,55); parameterized constructor
time t3; //default constructor
clrscr();
//addition of 2 times
//calling sum function with object as function argument and with return value
t3=t1.sum(t2);
//t3=t1+t2;
cout<<"time 1 ="<<endl;
t1.puttime();
cout<<"time t2="<<endl;
t2.puttime();
cout<<"time 3="<<endl;
t3.puttime();
}

Copy Constructor

- It takes a reference to the object of the same class as itself as an argument.


- It is used to declare and initialize an object from another object.
//copycons.cpp
//copy constructor

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class copy
{
//private data members
int id;
public:
//default constructor definition
copy()
{
};
//parameterised constructor definition
copy(int a)
{
id=a;
}
//copy constructor
copy(copy &x)
{
id=x.id; //copying the value

CHANDRA MOULI (DEPT OF CS in KU) Page 31


9640235390
PROGRAMMING IN C++

void display(void)
{
cout<<"id value = "<<id<<endl;
}
};

void main()
{
copy A(11); //object A is created and initialized
copy B(A); // copy constructor called
copy C=A; // copy constructor called again
copy D;// object D is created but not initialized
D=A; // copy constructor called again
clrscr();
cout<<"value of id of A="<<endl;
A.display();
cout<<"value of id of B="<<endl;
B.display();
cout<<"value of id of C="<<endl;
C.display();
cout<<"value of id of D="<<endl;
D.display();
}

Destructors

As the name indicates, it is used to destroy the objects that have been created by a constructor.
- Like a constructor, destructor is a member function whose name is same as the class name but it
is preceded by a tilde symbol(~)

Characteristics
. Declared in public section
. Has same name as that of class name but preceded by tilde symbol ( ~ )
. Does not return any value

//defcons.cpp
///class with default constructor & destructor
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class destruct //classname
{
//private data members
int a,b,c;

CHANDRA MOULI (DEPT OF CS in KU) Page 32


9640235390
PROGRAMMING IN C++

public:
//default constructor definition
destruct(void)
{
a=5; //giving initial values to data members a and b
b=10;
}
//destructor function definition
~destruct(void)
{
clrscr();
cout<<" value of a ="<<a<<endl;
cout<<" value of b ="<<b<<endl;
c=a+b;
cout<<"sum is "<<c<<endl;
}
};

void main()
{
destruct des; //default constructor
}

Inheritance: Extending Classes


The mechanism of deriving a new class from old one is called inheritance or derivation. The old
class is referred as base or parent class or super class and new class is referred as derived or child class
or sub class.
The derived class inherits some or all of the traits/properties of the base class. In OOPs, the
concept of Inheritance provides the idea of reusability which means that we can add additional features to
the existing class without modifying it. This is possible by deriving a new class from the existing class.
The new class will have the combined features of both the classes.

Advantages of inheritance

-Reusability
- Avoiding duplication of code
- Time
- Speed

Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

Defining a derived class

CHANDRA MOULI (DEPT OF CS in KU) Page 33


9640235390
PROGRAMMING IN C++

A derived class is defined by specifying its relationship with the class in addition to its own details.

Class derivedclassname:visibility mode baseclassname


{
=========
//members of derived class

};
- The : colon indicates that the derivedclassname is derived from the baseclassname.
- The visibility mode is optional. If present, it can be either private or public.
- The default visibility mode is private which specifies that whether the features of the base class
are privately derived or publicly derived.

Private Derivation
When base class is privately inherited by a derived class, “public members” of the base class
become “private members” of the derived class and therefore the public members of the base class only
are accessed by the member functions of the derived class. They are inaccessible to the objects of the
derivedclass.

Public Derivation
When the base class is publicly inherited, “public members” of the base class becomes “public
members” of the derived class and therefore they are accessible to the objects of the members of a
derived class.

Single Inheritance

A derived class has only one base class.

Diagram

//sngleinh.cpp
//single inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class base
{
//private data members
int a; //not inheritable
public:
int b; //ready for inheritance
void getab(void);
int geta(void);
CHANDRA MOULI (DEPT OF CS in KU) Page 34
9640235390
PROGRAMMING IN C++

void show(void);
};

//derived class

class derived : public base //public derivation


{
int c;
public:
void mul(void);
void display(void);
};

//function definitions outside class


void base :: getab(void)
{
a=5;
b=10;
}

int base :: geta(void)


{
return a;
}

void base :: show(void)


{
cout<<"value of a ="<<a<<endl;
}

void derived :: mul(void)


{
c=b*geta();
}

void derived :: display(void)


{
cout<<"value of a ="<<geta()<<endl;
cout<<"value of b ="<<b<<endl;
cout<<"value of c ="<<c<<endl;
}

void main()
{
derived d; // derived class object
clrscr();
d.getab();
d.mul();
d.show();
d.display();

CHANDRA MOULI (DEPT OF CS in KU) Page 35


9640235390
PROGRAMMING IN C++

// d.a=30; //not accessible as it is private


d.b=20;
d.mul();
d.display();
}

Making private member inheritable


The private member of a base class cannot be inherited and therefore it is not available for the
derived class directly. To inherit the private member at any cost, need to be made as public which will be
accessible to all other functions of the program thus eliminating the advantage of data hiding.

Protected C++ provide third visibility modifier called protected. A member declared as protected is
accessible by the member functions within a class and any class immediately derived from it. It cannot be
accessed by the functions outside these two classes.

Example:
class sample
{
private: //optional
==== //visible to member functions within its class
---------
protected:
--------- //visible to member functions of its own and also derived class
---------
public:
--------- // visible to all functions in the program
----------
};

Multilevel Inheritance
Mechanism of deriving a Class from another derived class is known as Multilevel Inheritance.

Diagram

//mulvlinh.cpp
//implementation of Multi level inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//base class
class student
{
//private data members
int rno;
char name[16];
public:
void getstuddetails(void)
{
cout<<"enter roll number and name"<<endl;
cin>>rno>>name;

CHANDRA MOULI (DEPT OF CS in KU) Page 36


9640235390
PROGRAMMING IN C++

}
void putstuddetails(void)
{
cout<<" roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}
};

//intermediate base class


class marks : public student
{
protected:
int sub1,sub2,sub3;

public:
void getmarks(void)
{
cout<<"enter any 3 subject marks"<<endl;
cin>>sub1>>sub2>>sub3;
}

void putmarks(void)
{
cout<<"sub1 marks ="<<sub1<<endl;
cout<<"sub2 marks ="<<sub2<<endl;
cout<<"sub3 marks ="<<sub3<<endl;
}
};

//derived class
class result : public marks
{
private:
int total;
float avg;
public:
void caluculate(void)
{
total=sub1+sub2+sub3;
avg=total/3;
}
//nesting of member functions
void displayresult(void)
{
putstuddetails(); //nesting of functions
putmarks();
cout<<"total marks ="<<total<<endl;
cout<<"average marks="<<avg<<endl;
}
};

CHANDRA MOULI (DEPT OF CS in KU) Page 37


9640235390
PROGRAMMING IN C++

void main()
{
result r; //derived class object
clrscr();
r.getstuddetails();
r.getmarks();
r.caluculate();
// r.putstuddetails();
// r.putmarks();
r.displayresult();
}

Multiple Inheritance

A class with several base classes is known as multiple inheritance.

Diagram

Syntax:
Class D: visibility B-1, visibility B-2,
{
====
====
Body of D
};

//multiinh.cpp
//implementation of multiple inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//base class1
class base1
{
protected:
int a;
public:
void geta(int x)
{
a=x;
}
};

//base class2
class base2
{
protected:
int b;
public:

CHANDRA MOULI (DEPT OF CS in KU) Page 38


9640235390
PROGRAMMING IN C++

void getb(int y)
{
b=y;
}
};

//derived class
class derived : public base1,public base2
{
public:
void display(void)
{
cout<<"value of a="<<a<<endl;
cout<<"value of b ="<<b<<endl;
cout<<"a + b ="<<a+b<<endl;
}
};

void main()
{
derived d; //derived class object
clrscr();
d.geta(4);
d.getb(5);
d.display();
}

Hierarchical Inheritance
In this form, the properties of one class are inherited by more than one class.

Diagram

//hirarcin.cpp
//implementation of Hierarchical Inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//base class
class student
{
int rno;
char *name; //char pointer
public:
void getstuddetails(int r,char *n)
{
rno=r;
name=n;
}

CHANDRA MOULI (DEPT OF CS in KU) Page 39


9640235390
PROGRAMMING IN C++

void putstuddetails(void)
{
cout<<"roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}

};

//derived class1
class internal1 : public student
{
private:
int sub1,sub2,sub3;
public:
void getinternal1marks(int s1,int s2,int s3)
{
sub1=s1;
sub2=s2;
sub3=s3;
}

void putinternal1marks(void)
{
cout<<"subject1 marks="<<sub1<<endl;
cout<<"subject2 marks="<<sub2<<endl;
cout<<"subject2 marks="<<sub3<<endl;
}
};

//derived class2
class internal2 : public student
{
private:
int sub1,sub2,sub3;
public:
void getinternal2marks(int s1,int s2,int s3)
{
sub1=s1;
sub2=s2;
sub3=s3;
}
void putinternal2marks(void)
{
cout<<"subject1 marks="<<sub1<<endl;
cout<<"subject2 marks="<<sub2<<endl;
cout<<"subject2 marks="<<sub3<<endl;
}
};

CHANDRA MOULI (DEPT OF CS in KU) Page 40


9640235390
PROGRAMMING IN C++

void main()
{
internal1 i1;
internal2 i2;
clrscr();
i1.getstuddetails(11,"chinnu");
i1.getinternal1marks(34,45,56);

cout<<"Student Details"<<endl;
i1.putstuddetails();
cout<<"Internal1 marks"<<endl;
i1.putinternal1marks();

i2.getinternal2marks(44,55,66);

cout<<"Internal2 marks"<<endl;
// i2.putstuddetails();
i2.putinternal2marks();
}

Hybrid Inheritance
This form of inheritance combines two or more forms of inheritancei.e.
combination of multiple and multilevel inheritance.

Diagram
//hybrdinh.cpp
//implementation of Hybrid Inheritance
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
//base class1
class student
{
//private data members
int rno;
char name[16];
public:
void getstuddetails(void)
{
cout<<"enter roll number and name"<<endl;
cin>>rno>>name;
}
void putstuddetails(void)
{
cout<<" roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}
};

//intermediate base class

CHANDRA MOULI (DEPT OF CS in KU) Page 41


9640235390
PROGRAMMING IN C++

class marks : public student


{
protected:
int sub1,sub2,sub3;
public:
void getmarks(void)
{
cout<<"enter any 3 subject marks"<<endl;
cin>>sub1>>sub2>>sub3;
}

void putmarks(void)
{
cout<<"sub1 marks ="<<sub1<<endl;
cout<<"sub2 marks ="<<sub2<<endl;
cout<<"sub3 marks ="<<sub3<<endl;
}
};

//baseclass2
class sports
{
protected:
float sportswtg;
public:
void getsportswtg(float s)
{
sportswtg=s;
}
void putsportswtg(void)
{
cout<<"sports weightage="<<sportswtg<<endl;
}
};

//derived class
class result : public marks,public sports
{
private:
int total;
float avg;
public:
void caluculate(void)
{
total=sub1+sub2+sub3+sportswtg;
avg=total/4;
}

//nesting of member functions

CHANDRA MOULI (DEPT OF CS in KU) Page 42


9640235390
PROGRAMMING IN C++

void displayresult(void)
{
putstuddetails();
putmarks();
putsportswtg();
cout<<"total marks ="<<total<<endl;
cout<<"average marks="<<avg<<endl;
}
};

void main()
{
result r; //derived class object
clrscr();
r.getstuddetails();
r.getmarks();
r.getsportswtg(5.0);
r.caluculate();
// r.putstuddetails();
// r.putmarks();
clrscr();
r.displayresult();
}

Multipath Inheritance - creation of class from other super class which are derived from common
super class

It is the inheritance where all three kinds of inheritance namely multiple, multilevel and hierarchical
inheritance are involved.

Grandparent

Parent1 parent2

Child

The child has two “direct base classes” i.e. “parent1” and “parent2” which themselves have a common
base class “grandparent”. The child inherits the properties of “grandparent” via two separate paths i.e.
parent1 and parent2. It can also inherit directly as shown above by the broken line. The “grandparent” is
referred as “indirect base class”.
Inheritance by the “child” as shown above cause certain problems. All the public & protected members of
“grandparent” are inherited into “child” twice, first via “parent1” and again via “parent2”. This means,
“Child” would have duplicate set of members inherited from “grandparent”. This introduces ambiguity
and should be avoided.
Note : The dotted line indicates that D inherits from A indirectly
//multipath.cpp
//implementation of Multipath Inheritance
#include<iostream.h>

CHANDRA MOULI (DEPT OF CS in KU) Page 43


9640235390
PROGRAMMING IN C++

#include<conio.h>
#include<iomanip.h>

//ancestor base class


class student
{
//private data members
int rno;
char name[16];
public:
void getstuddetails(void)
{
cout<<"enter roll number and name"<<endl;
cin>>rno>>name;
}
void putstuddetails(void)
{
cout<<" roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}
};
//intermediate baseclass1
class marks : public student
{
protected:
int sub1,sub2,sub3;
public:
void getmarks(void)
{
cout<<"enter any 3 subject marks"<<endl;
cin>>sub1>>sub2>>sub3;
}

void putmarks(void)
{
cout<<"sub1 marks ="<<sub1<<endl;
cout<<"sub2 marks ="<<sub2<<endl;
cout<<"sub3 marks ="<<sub3<<endl;
}
};

//intermediate baseclass2
class sports : public student
{
protected:
float sportswtg;
public:
void getsportswtg(float s)
{
sportswtg=s;

CHANDRA MOULI (DEPT OF CS in KU) Page 44


9640235390
PROGRAMMING IN C++

}
void putsportswtg(void)
{
cout<<"sports weightage="<<sportswtg<<endl;
}
};

//derived class
class result : public marks,public sports
{
private:
int total;
float avg;
public:
void displayresult(void)
{
total=sub1+sub2+sub3+sportswtg;
avg=total/4;
putstuddetails();
putmarks();
putsportswtg();
cout<<"total marks ="<<total<<endl;
cout<<"average marks="<<avg<<endl;
}
};

void main()
{
result r; //derived class object
clrscr();
r.getstuddetails();
r.getmarks();
r.getsportswtg(5.0);
r.displayresult();
}

O/p displays error as result as child is inheriting duplicate set of properties of student twice via marks and
sports.

Virtual Base Classes


The duplication of inherited members due to multiple paths ( above example) can be avoided by making
the common base class(ancestor class) as a virtual base class while declaring the direct or intermediate
base classes.
ie class marks : public virtual student
class sports : virtual public student

//mltpthvr.cpp
//implementation of Multipath Inheritance using virtual base classes
#include<iostream.h>

CHANDRA MOULI (DEPT OF CS in KU) Page 45


9640235390
PROGRAMMING IN C++

#include<conio.h>
#include<iomanip.h>

//ancestor base class


class student
{
//private data members
int rno;
char name[16];
public:
void getstuddetails(void)
{
cout<<"enter roll number and name"<<endl;
cin>>rno>>name;
}
void putstuddetails(void)
{
cout<<" roll number="<<rno<<endl;
cout<<"name ="<<name<<endl;
}
};
//intermediate baseclass1
class marks : virtual public student
{
protected:
int sub1,sub2,sub3;
public:
void getmarks(void)
{
cout<<"enter any 3 subject marks"<<endl;
cin>>sub1>>sub2>>sub3;
}

void putmarks(void)
{
cout<<"sub1 marks ="<<sub1<<endl;
cout<<"sub2 marks ="<<sub2<<endl;
cout<<"sub3 marks ="<<sub3<<endl;
}
};

//intermediate baseclass2
class sports : public virtual student
{
protected:
float sportswtg;
public:
void getsportswtg(float s)
{
sportswtg=s;

CHANDRA MOULI (DEPT OF CS in KU) Page 46


9640235390
PROGRAMMING IN C++

}
void putsportswtg(void)
{
cout<<"sports weightage="<<sportswtg<<endl;
}
};

//derived class
class result : public marks,public sports
{
private:
int total;
float avg;
public:
void displayresult(void)
{
total=sub1+sub2+sub3+sportswtg;
avg=total/4;
putstuddetails();
putmarks();
putsportswtg();
cout<<"total marks ="<<total<<endl;
cout<<"average marks="<<avg<<endl;
}
};

void main()
{
result r; //derived class object
clrscr();
r.getstuddetails();
r.getmarks();
r.getsportswtg(5.0);
r.displayresult();
}

Polymorphism
It is one of the important features of OOPs which means “one name, multiple forms”. It is the ability
to take more than one form.
Types of polymorphism
1. Compile-time polymorphism
2. Run-time polymorphism

Compile-time polymorphism
The overloaded functions are “Selected” for invoking by matching arguments, both type and
number. This information is known to the compiler at the compile time and, therefore, compiler is able to
select the appropriate function for a particular call at the compile time itself. This is called early binding
or static binding or static linking. Early binding simply means that an object is bound to its function
call at runtime.
Compile-time polymorphism can be achieved in C++ using the concepts

CHANDRA MOULI (DEPT OF CS in KU) Page 47


9640235390
PROGRAMMING IN C++

- Function overloading
- Operator overloading

Function overloading
Overloading refers to performing many tasks by single person.
Function overloading refers to calling a function having same name many number of times but
performing different set of activities and the same is identified by the compiler depending on the number
and type of arguments.

//funcover.cpp
//function overloading
//addition of 2 characters, 2 integers & 2 floating values

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>

//function prototyping
char add(char,char);
int add(int,int);
float add(float,float);

//main or calling program


main()
{
char a,b,p;
int c,d,q;
float e,f,r;
clrscr();
cout<<"enter any 2 character values"<<endl;
cin>>a>>b;
cout<<"enter any 2 integer values"<<endl;
cin>>c>>d;
cout<<"enter any 2 floating value"<<endl;
cin>>e>>f;

//calling a function
//call by value
p=add(a,b);
q=add(c,d);
r=add(e,f);
cout<<"additon of"<<a<<" + "<<b<<" is :"<<p<<endl;
cout<<"additon of"<<c<<" + "<<d<<" is :"<<q<<endl;
cout<<"additon of"<<e<<" + "<<f<<" is :"<<r<<endl;
return(0);
}

//called or sub program


//characters addition

CHANDRA MOULI (DEPT OF CS in KU) Page 48


9640235390
PROGRAMMING IN C++

char add(char x,char y)


{
return(x+y);
}

//integer additon
int add(int m,int n)
{
return(m+n);
}

//floating addition
float add(float r,float s)
{
return(r+s);
}
Example : 2
//funcover1.cpp
//function overloading
//drawing lines in different designs

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>

//function prototyping
void line(void);
void line(char);
void line(int);
void line(char,int);
//main or calling program
main()
{
clrscr();
//calling a function
//call by value
line();
line('*');
line(70);
line('=',80);
return(0);
}

//called or sub program


//characters addition
void line(void)
{
for(int i=1;i<=50;i++)
{

CHANDRA MOULI (DEPT OF CS in KU) Page 49


9640235390
PROGRAMMING IN C++

cout<<"-";
}
cout<<endl;
}

void line(char x)
{
for(int i=1;i<=60;i++)
{
cout<<x;
}
cout<<endl;
}

void line(int m)
{
for(int i=1;i<=m;i++)
{
cout<<"+";
}
cout<<endl;
}

void line(char p,int n)


{
for(int i=1;i<=n;i++)
{
cout<<p;
}
cout<<endl;
}

Operator overloading
Operator overloading refers to giving additional/special meaning to an operator.

Operators that cannot be overloaded


- Class member access operators (. , .*)
- Scope resolution operator ( : : )
- Size operator (sizeof)
- Conditional operator (? and :
Defining operator overloading
Additional task of an operator can be defined using a special function called operator function by
specifying what it means in relation to the class to which the operator is applied

Syntax:

return typeclassname :: operator op(argument list)


{
function body //task defined
}

CHANDRA MOULI (DEPT OF CS in KU) Page 50


9640235390
PROGRAMMING IN C++

Steps for creating operator overloading


 First, create a class that defines the data type that is to be used in the overloading operation.
 Declare the operator function operator op in the public part of the class which may be either a
member or friend function.
 Define the operator function to implement the required operations.

Overloading of unary operators


Unary operators are those operators which take single operand in performing an operation.
Example:
Unary +
Unary –
Increment (++) and decrement (--) operators

//ovrlodum.cpp
//overloading of unary minus operator
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class unaryminus
{
//private data members
int a,b,c;
public:
//getting data
void getdata(int p,int q,int r)
{
a=p;
b=q;
c=r;
}
// putting data
void putdata(void)
{
cout<<"value of a="<<a<<endl;
cout<<"value of b="<<b<<endl;
cout<<"value of c="<<c<<endl;
}

//overloading unary minus operator fuction definition


void operator - ()
{
a=-a;
b=-b;
c=-c;
}
};

CHANDRA MOULI (DEPT OF CS in KU) Page 51


9640235390
PROGRAMMING IN C++

void main()
{
unaryminus um; //object
clrscr();
um.getdata(5,-10,15);
cout<<"Before overloading unary minus operator"<<endl;
um.putdata();
-um; //overlaoding unary minus - operator
cout<<"After overloading unary minus operator"<<endl;
um.putdata();
}

//ovrlodui.cpp
//overloading of unary pre increment operator
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class unaryincrement
{
//private data members
int a,b,c;
public:
//getting data
void getdata(int p,int q,int r)
{
a=p;
b=q;
c=r;
}
// putting data
void putdata(void)
{
cout<<"value of a="<<a<<endl;
cout<<"value of b="<<b<<endl;
cout<<"value of c="<<c<<endl;
}

//overloading unary pre increment operator function definition


void operator ++ ()
{
a=++a;
b=++b;
c=++c;
}
};

void main()

CHANDRA MOULI (DEPT OF CS in KU) Page 52


9640235390
PROGRAMMING IN C++

{
unaryincrement uin; //object
clrscr();
uin.getdata(5,-10,15);
cout<<"Before overloading unary pre increment operator"<<endl;
uin.putdata();
++uin; //overloading unary pre increment operator
cout<<"After overloading unary pre increment operator"<<endl;
uin.putdata();
}

Overloading of Binary Operators


Binary operators are those operators which takes two operands for an operation.

Example:
binary +, binary - , binary *, binary *

//ovrlodbp.cpp
// binary operator over loading (+)
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class demo
{
private:
int a;
public:
void read()
{
cout<<"enter a value"<<endl;
cin>>a;
}
void print()
{
cout<<"a ="<<a<<endl;
}
demo operator +(demo b)
{
demo res;
res.a=a+b.a;
return res;
}
};

void main()
{
demo a,b;
clrscr();

CHANDRA MOULI (DEPT OF CS in KU) Page 53


9640235390
PROGRAMMING IN C++

a.read( );
b.read( );
a=a+b; //operator overloading function
a.print( );
}

Run-time polymorphism
A member function can be selected while the program is running. This is known as run-time
polymorphism. C++ supports a mechanism known as virtual functions to achieve runtime polymorphism.
Since the function is linked with a particular class much later after the compilation, this process is termed
as late binding. It is also known as dynamic binding because the selection of the appropriate function call
is done dynamically at runtime.
Pointers
It is a variable that holds the address of another variable.

Pointers to Objects (Base Class)


It is possible to access class member using pointers.

Example:
item x;
Where item is a class and x is an object of type class item
Similarly, we can define a pointer of type class item
Example:
item *itptr; //object pointer

Object pointers are useful in creating objects at run time. We can also use an object pointer to access the
public members of an object.

Let us declare an item variable x and a pointer itptr to x as follows

item x; /base class object


item *itptr; //base class pointer
itptr=&x;
The pointer itptr is initialized with the address of x.

We can refer the member functions of item in 2 ways, one by using dot operator and the object, and
another by using the arrow operator and the object pointer.

1) x.getdata(5,10);
x.show ();

The above statements are equivalent to


2) itptr->getdata(5,10);
itptr->show ();

Since *itptr is an alias of x, we can also use as

(*itptr).show ();

CHANDRA MOULI (DEPT OF CS in KU) Page 54


9640235390
PROGRAMMING IN C++

//ptrtoobj.cpp
//baseptr.cpp
//pointer to objects (Base Class)
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class item
{
//private data members
int icode;
float price;
public:
void getitemdetails(int a,float b)
{
icode=a;
price=b;
}
void putitemdetails(void)
{
cout<<" item code ="<<icode<<endl;
cout<<" price of item ="<<price<<endl;
}
};

void main()
{
item x,*ptr; //declaration of pointer ptr of type class item
ptr=&x; //initialising the address of object to pointer ptr
clrscr();
//x.getitemdetails(11,100);
//x.putdetails();
ptr->getitemdetails(11,100);
//ptr->putitemdetails();
(*ptr).putitemdetails();
}
Pointers to Derived Classes
Pointers can be used not only to the base class but also to the derived classes. Pointers to objects
of a base class are type compatible with pointers to objects of derived class. Therefore, a single pointer
variable can be made to point to objects belonging to different classes.
For example, if B is a base class and D is a derived class from B, then a pointer declared
as a pointer to B can also be a pointer to D.

B *bptr; // pointer to base class B


B b; //base class object
D d; //derived class object
bptr=&b; //base class pointer bptr pointing to base class object b
We can make base class pointer bptr to point to the derived class object d as follows

bptr=&d; //base class pointer bptr is pointing to derived class object d

CHANDRA MOULI (DEPT OF CS in KU) Page 55


9640235390
PROGRAMMING IN C++

It is valid because d is an object derived from base class B.

However, there is a problem in using bptr to access the public members of the derived class D.
Using bptr, we can access only those members inherited from B and not the members that originally
belonging to D.

NOTE:
- In case a member of D has the same name as one of the members of B, then any reference to
that member by bptr will always access the base class member.
- Although C++ permits a base pointer to point to any object derived from that base, the
pointer cannot be directly used to access all the members of the derived class. In that case, we
have to use anotherpointer declared as pointer to the derived type.

NOTE:
Though a base pointer can be made to point to any number of derived objects, it cannot directly
access the members defined by a derived class.

//dervdptr.cpp
//pointer to derived class objects
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

//base class
class base
{
public:
int b;
void show(void)
{
cout<<"value of base class b="<<b<<endl;
}
};

//derived class
class derived : public base
{
public:
int d;
void show(void)
{
cout<<"value of base class b="<<b<<endl;
cout<<"value of derived class d="<<d<<endl;
}
};

void main()
{
clrscr();

CHANDRA MOULI (DEPT OF CS in KU) Page 56


9640235390
PROGRAMMING IN C++

//base class
base bb; //base class object
base *bptr; //base class pointer
bptr=&bb; //base class pointer pointing to address of base class object

bptr->b=15; //accessing baseclass b member via base class pointer


cout<<"Base class pointer bptr pointing to base class object"<<endl;
bptr->show(); // access base class method using base class pointer

//derived class
derived dd; //derived class object
bptr=&dd; //baseclass pointer pointing to the address of derived class object
bptr->b=20; //accessing base class member b thru base class pointer
/* bptr->d=25; */ // accessing derived class member d thru base class
//pointer which does not work
cout<<"base class pointer bptr now points to derived class object"<<endl;

// access derived class member d using derived class pointer

derived *dptr; //derived class pointer


dptr=&dd; // derived class pointer dptr pointing to derived class object dd
dptr->d=30;
cout<<"dptr is derived type pointer"<<endl;
dptr->show();
}

Virtual functions
Though, the base class pointer is pointed to the derived class objects, it executes the function in
the base class but not from the derived class. This problem can be avoided using the concept called
“virtual functions”.
When a function with same name is declared in both the base and derived classes, the function in
base class is declared as virtual, C++ determines which function to be called at run time based on the type
of the object pointed by the pointer, rather than the type of the pointer. Thus, by making the pointer to
point to different objects.

Rules for virtual functions


1. The virtual functions must be members of some class
2. They cannot be static members
3. They are accessed using object pointers
4. A virtual function can be a friend of other class
5. A virtual function in a base class must be defined, even though it may not be used
6. The prototypes of thebase class version of a virtual function and all the derived class versions
must be identical.

//pointer to derived class objects


//virtual functions
//virtual.cpp
#include<iostream.h>
#include<conio.h>

CHANDRA MOULI (DEPT OF CS in KU) Page 57


9640235390
PROGRAMMING IN C++

#include<iomanip.h>

//base class
class base
{
public:
int b;
void virtual show(void)
{
cout<<"iam in base class"<<endl;
cout<<"value of base class b="<<b<<endl;
}
};

//derived class
class derived : public base
{
public:
int d;
void virtual show(void)
{
cout<<"iam in derived class"<<endl;
cout<<"value of base class b="<<b<<endl;
cout<<"value of derived class d="<<d<<endl;
}
};

void main()
{
clrscr();
//derived class
derived dd,*dptr; //derived class object
dptr=&dd; //derivedclass pointer pointing to the address of derived class object
dptr->b=20; //accessing base class member b thru derived class pointer
dptr->d=25; // accessing derived class member d thru derived class pointer
dptr->show();
}

Operator Overloading
The mechanism of giving special meaning to an operator is known as operator overloading.

Note: All the operators of C++ can be overloaded except the following
-
Operators that cannot be overloaded
. Class member access operators (. *)
. Scope resolution operator (:: )
. Size operator (size of)
. Conditional operator (? And :)

Defining Operator overloading

CHANDRA MOULI (DEPT OF CS in KU) Page 58


9640235390
PROGRAMMING IN C++

Additional task to an operator can be specified with the help of a special function called operator
functionwhich describes the task.

Syntax:

returntype classname :: operator op (argument-list)


{
function body // task defined
}

Steps
Process of overloading involves the following steps
1. First, create a class that defines the data types that is to be used in the overloading operation
2. Declare the operator function operator op ( ) in the public part of the class. It may be either a
member function or a friend function
3. Define the operator function to implement the required operations

Operator
It is symbol to perform an operation.

Types of operators
1. Unary operators
2. Binary operators
3. Ternary operators

Unary operators
Unary operators are those operators which takes single operator to perform an operation.

Example:
unary + (plus)
unary – (minus)
increment operator - ++
decrement operator - --

Overloading unary minus (-) operators


A minus operator, when used as unary, takes just one operand, which changes the sign of an
operand when applied to basic data item.
//ovrlodum.cpp
//overloading of unary minus operator
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class unaryminus
{
//private data members
int a,b,c;

CHANDRA MOULI (DEPT OF CS in KU) Page 59


9640235390
PROGRAMMING IN C++

public:
//getting data
void getdata(int p,int q,int r)
{
a=p;
b=q;
c=r;
}
// putting data
void putdata(void)
{
cout<<"value of a="<<a<<endl;
cout<<"value of b="<<b<<endl;
cout<<"value of c="<<c<<endl;
}

//overloading unary minus operator fuction definition


void operator - ()
{
a=-a;
b=-b;
c=-c;
}
};

void main()
{
unaryminus um;
clrscr();
um.getdata(5,-10,15);
cout<<"Before overloading unary minus operator"<<endl;
um.putdata();
-um; //overlaoding unary minus - operator
cout<<"After overloading unary minus operator"<<endl;
um.putdata();
}

Binary Operators
These are those operators which takes two operands for operation.

Example: binary + , binary -, binary *, binary /

Ex: a+b;
a-b;

Two numbers can be added using


c=sum(a,b); // functional notation
c=a+b; // arithmetic notation

CHANDRA MOULI (DEPT OF CS in KU) Page 60


9640235390
PROGRAMMING IN C++

// similarly, two objects of type time can be added as


time3 = time1 + time2; //binary + operator to be overloaded

//addition of 2 times
//function with object as argument and with return value
//overloading binary plus operator

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class time
{
//private data members
int hours,minutes;
public:
//getting time
void gettime(int h,int m)
{
hours=h;
minutes=m;
}
//displaying time
void puttime(void)
{
cout<<" hours = "<<hours<<" and minutes ="<<minutes<<endl;
}

//overldbp.cpp or ovrlodb.cpp
//addition of 2 times
// binary plus operator overloading function definition
time operator + (time t2)
{
time t;
t.minutes=minutes+t2.minutes;
t.hours=t.minutes/60;
t.minutes=t.minutes%60;
t.hours=t.hours+hours+t2.hours;
return t;
}
};

void main()
{
time t1,t2,t3;
clrscr();
t1.gettime(3,45); //get time1

CHANDRA MOULI (DEPT OF CS in KU) Page 61


9640235390
PROGRAMMING IN C++

t2.gettime(4,55); //get time2


//addition of 2 times
t3=t1+t2; //overloading binary + operator
cout<<"time 1 ="<<endl;
t1.puttime();
cout<<"time t2="<<endl;
t2.puttime();
cout<<"time 3="<<endl;
t3.puttime();
}

Rules for operator overloading


1. Only existing operators can be overloaded
2. The overloaded operator must have atleast one operand that is user defined data type
3. We cannot change the basic meaning of an operator
4. Overloaded operators follow the syntax rules of original operators
5. Unary operators, overloaded by means of a member function, take no explicit arguments and
return no explicit values. But, those overloaded by means of a friend function take one reference
argument
6. Binary operators, overloaded by means of a member function, take one explicit arguments and
those overloaded by means of a friend function take two explicit arguments
7. When using binary operators overloaded through a member function, the left-hand operator must
be an object of the relevant class.

Inline functions
One of theobjectives of using functions in a program is to save memory space, which
becomes important when a function is likely to be called many times. However, every time a
function is called, it takes lot of time in executing series of instructions for tasks such as jumping
to the function, saving registers, pushing arguments into the stack and returning to the calling
function.
One solution to this problem is to use macro definitions known as macros. But the
drawback of it is that they are not really functions and therefore, the usual error checking does
not occur during compilation.
An inline function is a function that is expanded in inline when it is invoked. That is,
compiler replaces the function call with the corresponding function code.

Syntax:

inline functionheader
{
function body
}

//inlnefnc.cpp
//usage of inline functions
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

CHANDRA MOULI (DEPT OF CS in KU) Page 62


9640235390
PROGRAMMING IN C++

inline float mult(float a,float b) // inline function


{
return(a*b);
}

inline double div(double p,double q) // inline function


{
return(p/q);
}

void main()
{
float x=9.75;
float y=3.45;
clrscr();
cout<<mult(x,y)<<endl;
cout<<div(x,y)<<endl;
}

Friend Functions
Private data members are not accessible from outside the class. That is, a non member function
cannot have an access to the private data of a class.
There may be a situation where both the classes have to share the common function where in C++
allows the function to be made friendly with both the classes, thereby allowing the function to have
access to the private data of these classes. Such, a function need not be a member of any of these classes.
Functions that are declared with the keyword friend are called friend functions.

Syntax:
Friend returntype functionname(argument list); //declaration

Note:
1. The function declaration should be preceded by the keyword friend and the function is defined
elsewhere in the program like normal function.
2. The function definition does not use either the keyword friend or the scope operator ::

Characteristics of friend functions


1. It is not in the scope of the class to which it has been declared as friend
2. Since, it is not in the scope of the class, it cannot be called using the object of that class i.e. it can
be invoked like a normal function without the help of any object.
3. It can be declared either in the private or public part of a class without effecting its meaning.
4. Usually, it has the objects as arguments
5. Generally used in operator overloading
//frndfunc.cpp
//friendly function to two classes
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

class two; //farward declaration


class one

CHANDRA MOULI (DEPT OF CS in KU) Page 63


9640235390
PROGRAMMING IN C++

{
//private data members
int a;
public:
void getvalue(int aa)
{
a=aa;
}
//friend function declaration

friend void maximum(one,two);


};

class two
{
//private data members
int b;
public:
void getvalue(int bb)
{
b=bb;
}
//friend function declaration

friend void maximum(one,two);


};

//friend function definition outside the class

void maximum(one o,two t)


{
if(o.a >= t.b)
cout<<"class one value is greater"<<o.a<<endl;
else
cout<<"class two value is greater "<<t.b<<endl;
}

void main()
{
one onee;
clrscr();
onee.getvalue(10);
two twoo;
twoo.getvalue(20);
maximum(onee,twoo);
}

CHANDRA MOULI (DEPT OF CS in KU) Page 64


9640235390
PROGRAMMING IN C++

Managing I/O operations

- Console I/O operations – combination of keyboard and monitor


- Reading data from keyboard & writing data onto monitor
- Disk I/O operations - reading data from file and writing data onto file

C++ uses the concept of stream and stream classes to implement I/O operations with console and
disk files.

C++ Streams
A stream is a sequence of bytes which acts as either as a source from which the input data can be
obtained or as a destination to which the output data can be sent.
The source stream that provides data to the program is called input stream and the destination
stream that receives output from the program is called output stream.
In other words, a program extracts the bytes from an input stream and inserts bytes into an output
stream.

I/O operations
I/O operations are of 2 types namely
1. Unformatted I/O operations
2. Formatted I/O Operations

Unformatted I/O Operations


1) Overloaded >> and << operators
cin and cout objects predefined in iostream.h file are used for input and output of data of various
types is made possible by overloading the operators << and >> to recognize all basic data types.
The operator >> is overloaded in the istream class and << is overloaded in the ostream class.

Syntax:
cin>>variable1>>variable2>>…..variableN;
cout<<item1<<item2<<…..<<itemN;

Example:
int code;
cin>>code;
cout<<code;
2) put() and get() – character oriented functions
The classes istream and ostream define two member functions get() and put() to handle single
character i/o operations.
get() – gets a single character from keyboard
put() – writessingle character onto monitor

ex:
char ch;
cin.get(ch); // gets a character from keyboard and assigns it to variable ch

cout.put(ch); // displays the value of variable ch on monitor


3) getline() and write() functions –line oriented functions
Line of text can be read and displayed using line-oriented i/o functions getline() and write().

CHANDRA MOULI (DEPT OF CS in KU) Page 65


9640235390
PROGRAMMING IN C++

getline() – reads entire line of text that ends with new line character (enter key)

Syntax:
cin.getline(line,size);

example:
char name[26];
cin.getline(name,25);

write() – displays entire line of text on screen


syntax:
cout.write(line,size);

example:
cout.write(name,20);

Formatted Console I/O operations


These are so called because format of the data can be specified
1. format functions
Function task

Width() to specify the required field size for


displaying output value
precision() to specify the number of digits to be displayed after the
decimal point of float value
fill() to specify a character that is used to fill unused portion of
a field
setf() to specify format flags that can control the form of output
display
unsetf() to clear the flags specified

2. Manipulators
These are the parameters that can be included in I/O statements to alter the format parameters
of a stream.

Manipulators equivalent ios functions

setw() width()
setprecision() precision()
setfill() fill()
setiosflags() setf()
resetiosflags() unsetf()

defining field width using width()


cout.width(size);

example:

CHANDRA MOULI (DEPT OF CS in KU) Page 66


9640235390
PROGRAMMING IN C++

cout<<width(5);
cout<<123;
cout<<width(5);
cout<<34;

setting precision using precision()


By default, floating numbers are printed with six digits after the decimal point.

Cout.precison(nod);
Example:
Cout.precison(3);
Cout<<sqrt(3);

Filling and padding using fill()


By default, the unused portions of the field are filled with space.

Cout.fill(character);

Example:
Cout.fill(‘*’);
Cout.width(5);
Cout<<123;

Working with files (File Management)generally data stored in a variable is temporary and holds only
singleValue at a time and the same is lost whenever system is switched off.
To avoid the problem, external storage devices like hard disks can be used where the data is stored in
these devices using the concept of files.
File is a collection of records or related data stored in a particular area on the disk.
Record is a collection of fields
Field is a collection of characters but should have some meaning.

Streams
Stream is nothing but sequence of bytes. I/O system of C++ handles the file operations (Disk I/O)
which are very much similar to the console I/O operations. It uses file streams to act as interface between
the programs and the files.

File streams
The stream that supplies data to the program is known as input stream
and the one that receives the data from the program is known as output stream.
In other words, the input stream extracts or reads data from the file and the output stream inserts or writes
data to the file.

Fig 11.2 pg no 214

CHANDRA MOULI (DEPT OF CS in KU) Page 67


9640235390
PROGRAMMING IN C++

File stream classes

filebuf set the file buffers to read and write


fstreambase provides operations common to file streams.
serves as base for fstream,ifstream,ofstream classes
ifstream provides input operations. Contains open() with
default input mode.
inherits get(),getline(),read(),seekg(),tellg() from
istream.
ofstream provides output operations. Contains open() with
default output mode.
Inheritsput(),seekp(),tellp() fromostreamfstream
provides support for simultaneous i/o
operations. Contains open() with default input
mode. Inherits all the functions from istream
and ostream classes thru iostream.
NOTE: A file stream can be defined using the classes ifstream,ofstream and fstream classes that are
contained in the header file fstream.h.

Opening a file
A file can be opened either for reading/writing data in 2 ways
1. Using the constructor function of the class
2. Using the member function open() of the class

Opening file using constructor


1. Create a file stream object to manage the stream using appropriate class ie ofstream class to
create the output stream and ifstream class to create input stream
2. Initialize the file object with desired filename

Example :
ofstream outfile(“sample”); // opens file named sample for output only
note : if the file “sample” does not exist, it creates a new file. If exists, it overwrites the contents of
exisiting file.

ifstream infile(“sample”); // opens file named sample for input only

Opening file using open( )


file-stream-class stream-object;
stream-object.open (“filename”);

Example:
ofstream outfile; //creates stream for output
outfile.open(“sample”); //connects stream to sample
outfile.close(); // disconnects stream from sample

ifstream infile; //creates stream for input


infile.open(“sample”); //connects stream to sample

//file.cpp

CHANDRA MOULI (DEPT OF CS in KU) Page 68


9640235390
PROGRAMMING IN C++

//reading and writing of data from or to files


//working with files
#include<fstream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
ofstream outfile; // creates output stream
outfile.open("item",ios::app); // connect item file to outout
char iname[15];
int icost;
clrscr();
//getting details from keyboard
cout<<"enter item details like itemname and cost of item"<<endl;
cin>>iname>>icost;
//writing details onto item file
outfile<<iname;
outfile<<icost<<endl;
//closing of file
outfile.close();

ifstream infile; // creates input stream


infile.open("item"); // connects item file to input
infile>>iname;
infile>>icost;
cout<<"details of item are"<<endl;
cout<<"item name="<<iname<<endl;
cout<<"item cost="<<icost<<endl;
infile.close();
}

File organization
Specifies how the data in the file is organized.

Types of file organization


1. Sequential file organization
2. Random file organization

Sequential file organization


Allows to access data in the sequential manner i.e. from beginning of file till end of the file ie
pointer cannot be placed directly at desired location.

Random file organization


Allows to access data randomly i.e. pointer can be placed directly at desired location.

Detecting end of file


Detection of end of file condition is necessary for preventing any further attempt to read data
from the file.

CHANDRA MOULI (DEPT OF CS in KU) Page 69


9640235390
PROGRAMMING IN C++

Ex: while(infile)
An ifstream object, like infile returns a value of 0 if any error occurs in the file operation including the
end of file condition. Thus, the while loop terminates when infile returns a value of 0 on reaching the end
of file condition.

//program detecting end of file condition


//eof.cpp
//working with files
#include<fstream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
ofstream outfile; // creates output stream
outfile.open("item",ios::app); // connect item file to outout
char iname[15];
int icost;
clrscr();
//getting details from keyboard
for(int i=1;i<=3;i++)
{
cout<<"enter item details like itemname and cost of item"<<endl;
cin>>iname>>icost;
//writing details onto item file
outfile<<iname<<endl;
outfile<<icost<<endl;
}
//closing of file
outfile.close();

ifstream infile; // creates input stream


infile.open("item"); // connects item file to input
// for(int j=1;j<=10;j++)
//detecting end of file
while(infile)
{
infile>>iname;
infile>>icost;
cout<<"details of item are"<<endl;
cout<<"item name="<<iname<<endl;
cout<<"item cost="<<icost<<endl;
}
infile.close();
}

File opening modes


File opening mode specifies the need of opening a file.

streamobject.open(“filename”,”fileopeningmode”);

CHANDRA MOULI (DEPT OF CS in KU) Page 70


9640235390
PROGRAMMING IN C++

Fileopening mode parameters

ios::app appends data to end of file


ios::ate go to end of file on opening
ios::in opens file for reading only
ios::out opens file for writing only
ios::trunc deletes the contents of the file, if file exist

Command line arguments


C++ supports a feature that facilitates the supply of arguments to main () function. These
arguments are supplied at the time of invoking the program which are typically used to pass the names of
the data files.
Example:
C:>cmdline even odd
Here, cmdline is the name of the file containing the program to be executed(.cpp) and even, odd are the
filenames passed to the program as command-line arguments.
The command line arguments are typed by the user and are delimited by space. The first
argument is always the file name (command name) and contains the program to be executed.
The main() function can take arguments i.e. argc and argv[].
Syntax:
void main(int argc,char *argv[])
{
Function body;
}

The first argc is argument counter which represents the number of arguments in the command line.
The second argument argv is known as argument vector is an array of char type pointers that point to the
command line arguments. The size of the array will be equal to the value of argc.

Example:
C:>evenodd even odd
Here,
the value of argc will be 3
and
the argv would be an array of three pointers to strings as follows
argv[0] -> evenodd
argv[1] -> even
argv[2] -> odd
Note: argv[0] always represent the command name that invokes the program.

// command line arguments


//cmdline.cpp
#include<fstream.h>
#include<stdlib.h>
#include<conio.h>
#include<iomanip.h>
void main(int argc,char *argv[])
{

CHANDRA MOULI (DEPT OF CS in KU) Page 71


9640235390
PROGRAMMING IN C++

int num[10]={11,22,33,44,55,66,77,88,99,100};
if(argc !=3)
{
cout<<"number of arguments="<<argc<<endl;
cout<<"invalid number of arguments passed"<<endl;
exit(1);
}

//creation of stream objects for writing purpose


ofstream fout1,fout2;
//opening of file
fout1.open(argv[1]);
if(fout1.fail())
{
cout<<"sorry. cannot opend the file"<<argv[1]<<endl;
exit(1);
}

fout2.open(argv[2]);
if(fout2.fail())
{
cout<<"sorry. cannot open the file"<<argv[2]<<endl;
exit(1);
}

for(int n=0;n<=9;n++)
{
if(num[n]%2 == 0)
fout1<<num[n]<<endl; // as it is even writes to even file
else
fout2<<num[n]<<endl; // as it is odd writes to odd file
}
fout1.close();
fout2.close();

//creation of objects for reading


ifstream fin;
char ch;
for(int i=1;i<argc;i++)
{
fin.open(argv[i]); //reading
cout<<"contents of "<<argv[i]<<" are "<<endl;
do
{
fin.get(ch);
cout<<ch; // displays value of ch on screen
}while(fin); //testting end of file
cout<<endl;
fin.close();

CHANDRA MOULI (DEPT OF CS in KU) Page 72


9640235390
PROGRAMMING IN C++

getch();
}
}

Steps :
1. Save the program as cmdline.cpp
2. Compile , link and execute the program by pressing ctrl+f9 which creates
Cmdline.exe file
3. Chose file->dosshell which exit from windows temporarily to dos
4. At the Dos prompt, type C:>cmdline even odd

Templates
Templates allow us to define generic classes which can be used with various data types.
A template can be treated as a macro. When an object of specific type is defined for actual use,
the template definition for that class is substituted with the required data type. Since a template is
defined with a parameter that would be replaced by the special data type at the time of actual use of the
class or function, the templates are sometimes referred as parameterized classes or functions.

Template types

Templates are of 2 types namely


1. Class templates
2. Function templates

Class templates
Templates allow us to create generic classes. It is a simple process to create a generic class using
a template with an anonymous type.

Syntax:
Template <class T>

Class <classname>
{
// class member specification with anonymous type T wherever appropriate
};

//clstempl.cpp
//working with class templates
#include<iostream.h>
#include<conio.h>
template <class T>

class addition
{
T a,b,sum;
public:
addition()
{
a=b=sum=0;
}

CHANDRA MOULI (DEPT OF CS in KU) Page 73


9640235390
PROGRAMMING IN C++

addition(T x,T y)
{
a=x;
b=y;
}

void display(void)
{
cout<<"value of a ="<<a<<endl;
cout<<"value of b ="<<b<<endl;
cout<<" sum is "<<a+b<<endl;
}

T addition <T>:: add()


{
return (a+b);
}
};

void main()
{
addition <int> a1(10,20);
addition <float> a2(3.4,5.7);
int result1;
float result2;
clrscr();
result1=a1.add();
result2=a2.add();
a1.display();
a2.display();
}

Function templates
These are used to create a family of functions with different argument types.
Syntax:

Template <class T>


Returntype functionname(arguments of type T)
{
// function body with type T wherever appropriate
};

//working with function templates


//fnctemp.cpp

#include<iostream.h>
#include<conio.h>
template <class T>

CHANDRA MOULI (DEPT OF CS in KU) Page 74


9640235390
PROGRAMMING IN C++

class highest
{
T a,b;
public:
T highest(T x,T y)
{
return x>y?x:y;
}
};

void main()
{
highest <int> a1(4,5);
highest <float> a2(3.4,5.7);
int result1;
float result2;
clrscr();
result1=a1.highest();
cout<<result1;
result2=a2.highest();
cout<<result2<<endl;
}

Exception Handling
Bug is an error that is encountered during program execution. Whenever an error is encountered,
program is terminated in between without executing in a proper manner. To handle, that situation,
exceptions can be raised known as exception handling mechanism.
Exception handling is the latest feature added to C++. Exceptions refer to unusual conditions in a
program which can be taken care by exception handlers.
Exceptions are of 2 types namely, synchronous and asynchronous exceptions.

Synchronous exceptions: Errors like “out-of-range index” and “overflow”


Asynchronous exceptions: The errors that are caused by events beyond the control of the program like
keyboard interrupts.

The purpose of the exception handling mechanism is to provide means to detect and report an
“exceptional circumstance” so that appropriate action can be taken. The mechanism suggests a separate
error handling code that performs the following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take necessary actions (Handle the exception)

NOTE:
The error handling code consists of 2 segments; one to detect errors and to throw exceptions and
the other is to catch the exceptions and to take appropriate actions.

C++ uses 3 keywords namely try, catch and throw to handle exceptions.

CHANDRA MOULI (DEPT OF CS in KU) Page 75


9640235390
PROGRAMMING IN C++

When a function returns using the exception handling mechanism, it is referred to as throwing an
exception. The keywords “throw” implements this “return” activity.
The keyword try prefaces a block of statements which may generate exceptions.
A catch block defined by the keyword catch “catches” the exceptions “thrown” by throw and
handles them appropriately.

Exception handling mechanism figure – pg no : 275

CHANDRA MOULI (DEPT OF CS in KU) Page 76


9640235390
PROGRAMMING IN C++

CHANDRA MOULI (DEPT OF CS in KU) Page 77


9640235390
PROGRAMMING IN C++

CHANDRA MOULI (DEPT OF CS in KU) Page 78


9640235390

You might also like