C++ OOPS lecture notes all unit
C++ OOPS lecture notes all unit
ON
Object Oriented Programming Using C++
Prepared by
Object Oriented Programming Using Dr. Subasish Mohapatra
C++
2 P.T.O
1
SYLLABUS
PCCS2207 Object Oriented Programming
Module I CONTENTS
Introduction to object oriented programming, user defined types, structures, unions, Lecture 01: Introduction
polymorphism, encapsulation. Getting started with C++ syntax, data-type, variables, Lecture 02: Object Oriented Programming
strings, functions, default values in functions, recursion, namespaces, operators, flow Lecture 03: BASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMING
control, arrays and pointers. Lecture 04: BENEFITS OF OOP
Lecture 05: Basics of C++
Lecture 06: Tokens
Module II
Lecture 07: Basic Data types in C++
Abstraction mechanism: Classes, private, public, constructors, destructors, member data,
member functions, inline function, friend functions, static members, and references. Lecture 08: Symbolic Constant
Inheritance: Class hierarchy, derived classes, single inheritance, multiple, multilevel, Lecture 09: Operators
hybrid inheritance, role of virtual base class, constructor and destructor execution, base Lecture 10: Control Structures
initialization using derived class constructors. Lecture 11: Functions in C++
Polymorphism: Binding, Static binding, Dynamic binding, Static polymorphism: Function Lecture 12: Function Overloading
Overloading, Ambiguity in function overloading, Dynamic polymorphism: Base class
Lecture 13: Class
pointer, object slicing, late binding, method overriding with virtual functions, pure virtual
functions, abstract classes. Lecture 14: Member Function
Operator Overloading: This pointer, applications of this pointer, Operator function, Lecture 15: Nesting of Member function
member and non member operator function, operator overloading, I/O operators. Lecture 16: Array with Class
Exception handling: Try, throw, and catch, exceptions and derived classes, function Lecture 17: Static Data Member
exception declaration, unexpected exceptions, exception when handling exceptions, Lecture 18: Friendly functions
resource capture and release. Lecture 19: Returning Objects
Lecture 20: Constructors
Module III Lecture 21: Destructors
Dynamic memory management, new and delete operators, object copying, copy Lecture 22 & 23: Operator Overloading
constructor, assignment operator, virtual destructor. Lecture 24: Type Conversion
Template: template classes, template functions. Lecture 25: Class to Basic type
Standard Template Library: Fundamental idea about string, iterators, hashes, iostreams Lecture 26: Inheritance
and other types. Lecture 27: Multilevel Inheritance
Namespaces: user defined namespaces, namespaces provided by library.
Lecture 28: Hierarchical Inheritance
Object Oriented Design, design and programming, role of classes.
Lecture 29: Virtual Base Class
Lecture 30: Polymorphism
Text Books: Lecture 31: Virtual functions
1. Object Oriented Programming with C++ by E. Balagurusamy, McGraw-Hill Lecture 32: Pure Virtual Functions
Education (India) Lecture 33: C++ function overriding
2. ANSI and Turbo C++ by Ashoke N. Kamthane, Pearson Education
Lecture 34: Exception Handling
Reference Books: Lecture 35: Array reference out of bound
1. Big C++ - Wiley India Lecture 36: Containership in C++
2. C++: The Complete Reference- Schildt, McGraw-Hill Education (India) Lecture 37: Template
3. C++ and Object Oriented Programming – Jana, PHI Learning. Lecture 38: Class Template
4. Object Oriented Programming with C++ - Rajiv Sahay, Oxford Lecture 39: Virtual destructors
5. Mastering C++ - Venugopal, McGraw-Hill Education (India) Lecture 40: Managing Console I/O
Lecture 41: Namespaces
Lecture 42: New & Delete Operators
3 P.T.O 4 P.T.O
2
Module-1:
LECTURE-1
The first high-level programming languages were designed in the 1950s. Now there are dozens of
different languages, including Ada , Algol, BASIC, COBOL, C, C++, JAVA, FORTRAN, LISP, Characteristics of procedure oriented programming:
Pascal, and Prolog. Such languages are considered high-level because they are closer to human
languages and farther from machine languages. In contrast, assembly languages are considered low- 1. Emphasis is on doing things(algorithm)
level because they are very close to machine languages. 2. Large programs are divided into smaller programs known as functions.
3. Most of the functions share global data
4. Data move openly around the system from function to function
The high-level programming languages are broadly categorized in to two categories:
5. Function transforms data from one form to another.
6. Employs top-down approach in program design
(iv) Procedure oriented programming(POP) language.
(v) Object oriented programming(OOP) language.
5 P.T.O 6 P.T.O
3
LECTURE-3
LECTURE-2
BASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMING
Data Data
OBJECTS
Communication
Objects are the basic run-time entities in an object-oriented system. They may represent a person, a
Functions Functions place, a bank account, a table of data or any item that the program must handle.
The fundamental idea behind object oriented approach is to combine both data and function
into a single unit and these units are called objects.
Object C
The term objects means a combination of data and program that represent some real word
entity. For example: consider an example named Amit; Amit is 25 years old and his salary is 2500.
Functions The Amit may be represented in a computer program as an object. The data part of the object would
be (name: Amit, age: 25, salary: 2500)
The program part of the object may be collection of programs (retrive of data, change age,
Data change of salary). In general even any user –defined type-such as employee may be used. In the
Amit object the name, age and salary are called attributes of the object.
CLASS:
A group of objects that share common properties for data part and some program part are
collectively called as class.
In C ++ a class is a new data type that contains member variables and member functions that
operate on the variables.
7 P.T.O 8 P.T.O
4
DATA ABSTRACTION : MESSAGE PASSING :
Abstraction refers to the act of representing essential features without including the back An object oriented program consists of a set of objects that communicate with each
ground details or explanations. Classes use the concept of abstraction and are defined as size, width other.
and cost and functions to operate on the attributes.
A message for an object is a request for execution of a procedure and therefore will
DATA ENCAPSALATION : invoke a function (procedure) in the receiving object that generates the desired result. Message
passing involves specifying the name of the object, the name of the function (message) and
The wrapping up of data and function into a single unit (called class) is known as information to be sent.
encapsulation. The data is not accessible to the outside world and only those functions which are
wrapped in the class can access it. These functions provide the interface between the objects data and
the program. Employee . Salary (name)
INHERITENCE :
Inheritance is the process by which objects of one class acquire the properties of another Object Information
class. In the concept of inheritance provides the idea of reusablity. This mean that we can add Message
additional features to an existing class with out modifying it. This is possible by desining a new class
will have the combined features of both the classes.
POLYMORPHISIM:
Polymorphism means the ability to take more than one form. An operation may exhibit different
instance. The behaviour depends upon the type of data used in the operation.
A language feature that allows a function or operator to be given more than one definition. The types
of the arguments with which the function or operator is called determines which definition will be
used.
It is able to express the operation of addition by a single operater say ‘+’. When this is possible you
use the expression x + y to denote the sum of x and y, for many different types of x and y; integers ,
float and complex no. You can even define the + operation for two strings to mean the concatenation
of the strings.
DYNAMIC BINDING :
Binding refers to the linking of a procedure call to the code to the executed in
response to the call. Dynamic binding means the code associated with a given procedure call is not
known untill the time of the call at run-time. It is associated with a polymorphic reference depends
upon the dynamic type of that reference.
9 P.T.O 10 P.T.O
5
LECTURE-5
LECTURE- 4
Basics of C++
BENEFITS OF OOP:
C ++ is an object oriented programming language, C ++ was developed by Jarney
Oop offers several benefits to both the program designer and the user. Object-oriented contributes to Stroustrup at AT & T Bell lab, USA in early eighties. C ++ was developed from c and simula 67
the solution of many problems associated with the development and quality of software products. language. C ++ was early called ‘C with classes’.
The principal advantages are :
C++ Comments:
1. Through inheritance we can eliminate redundant code and extend the use of existing C++ introduces a new comment symbol //(double slash). Comments start with a
classes. double slash symbol and terminate at the end of line. A comment may start any where in the line and
2. We can build programs from the standard working modules that communicate with one what ever follows till the end of line is ignored. Note that there is no closing symbol.
another, rather than having to start writing the code from scratch. This leads to saving of The double slash comment is basically a single line comment. Multi line comments can be
development time and higher productivity. written as follows:
3. This principle of data hiding helps the programmer to build secure programs that can’t be
invaded by code in other parts of the program. // this is an example of
4. It is possible to have multiple instances of an object to co-exist with out any interference. // c++ program
5. It is easy to partition the work in a project based on objects. // thank you
6. Object-oriented systems can be easily upgraded from small to large systems. The c comment symbols /* ….*/ are still valid and more suitable for multi line comments.
7. Message passing techniques for communication between objects makes the interface
description with external systems much simpler. /* this is an example of c++ program */
8. Software complexity can be easily managed.
Output Operator:
APPLICATION OF OOP:
The statement cout <<”Hello, world” displayed the string with in quotes on the screen. The identifier
The most popular application of oops up to now, has been in the area of user interface cout can be used to display individual characters, strings and even numbers. It is a predefined object
design such as windows. There are hundreds of windowing systems developed using oop that corresponds to the standard output stream. Stream just refers to a flow of data and the standard
techniques. Output stream normally flows to the screen display. The cout object, whose properties are defined in
iostream.h represents that stream. The insertion operator << also called the ‘put to’ operator directs
Real business systems are often much more complex and contain many more objects the information on its right to the object on its left.
with complicated attributes and methods. Oop is useful in this type of applications because it
can simplify a complex problem. The promising areas for application of oop includes. Return Statement:
1. Real – Time systems. In C++ main ( ) returns an integer type value to the operating system. Therefore every main (
2. Simulation and modeling ) in C++ should end with a return (0) statement, otherwise a warning or an error might occur.
3. Object oriented databases.
4. Hypertext,hypermedia and expertext. Input Operator:
5. Al and expert systems.
6. Neural networks and parallel programming. The statement
7. Dicision support and office automation systems. cin>> number 1;
8. CIM / CAM / CAD system. is an input statement and causes. The program to wait for the user to type in a number. The number
keyed in is placed in the variable number1. The identifier cin is a predefined object in C++ that
corresponds to the standard input stream. Here this stream represents the key board.
The operator >> is known as get from operator. It extracts value from the keyboard
and assigns it to the variable on its right.
11 P.T.O 12 P.T.O
6
Cascading Of I/O Operator: executed in any C++ program. For that same reason, it is essential that all C++ programs have a main
function.
cout<<”sum=”<<sum<<”\n”; The word main is followed in the code by a pair of parentheses (()). That is because it is a function
cout<<”sum=”<<sum<<”\n”<<”average=”<<average<<”\n”; declaration: In C++, what differentiates a function declaration from other types of expressions are
cin>>number1>>number2; these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters
within them.
Right after these parentheses we can find the body of the main function enclosed in braces ({}).
Structure Of A Program : What is contained within these braces is what the function does when it is executed.
cout << "Hello World!";
Probably the best way to start learning a programming language is by writing a program. Therefore, This line is a C++ statement. A statement is a simple or compound expression that can actually
here is our first program: produce some effect. In fact, this statement performs the only action that generates a visible effect in
// my first program in C++ our first program.
cout represents the standard output stream in C++, and the meaning of the entire statement is to
#include <iostream> insert a sequence of characters (in this case the Hello World sequence of characters) into the standard
using namespace std; output stream (which usually is the screen).
cout is declared in the iostream standard file within the std namespace, so that's why we needed to
int main () include that specific file and to declare that we were going to use this specific namespace earlier in
{ our code.
cout << "Hello World!"; Notice that the statement ends with a semicolon character (;). This character is used to mark the end
return 0; of the statement and in fact it must be included at the end of all expression statements in all C++
} programs (one of the most common syntax errors is indeed to forget to include some semicolon after
Output:-Hello World! a statement).
The first panel shows the source code for our first program. The second one shows the result of the return 0;
program once compiled and executed. The way to edit and compile a program depends on the The return statement causes the main function to finish. return may be followed by a return code (in
compiler you are using. Depending on whether it has a Development Interface or not and on its our example is followed by the return code 0). A return code of 0 for the main function is generally
version. Consult the compilers section and the manual or help included with your compiler if you interpreted as the program worked as expected without any errors during its execution. This is the
have doubts on how to compile a C++ console program. most usual way to end a C++ console program.
The previous program is the typical program that programmer apprentices write for the first time, You may have noticed that not all the lines of this program perform actions when the code is
and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest executed. There were lines containing only comments (those beginning by //). There were lines with
programs that can be written in C++, but it already contains the fundamental components that every directives for the compiler's preprocessor (those beginning by #). Then there were lines that began
C++ program has. We are going to look line by line at the code we have just written: the declaration of a function (in this case, the main function) and, finally lines with statements (like
// my first program in C++ the insertion into cout), which were all included within the block delimited by the braces ({}) of the
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do main function.
not have any effect on the behavior of the program. The programmer can use them to include short The program has been structured in different lines in order to be more readable, but in C++, we do
explanations or observations within the source code itself. In this case, the line is a brief description not have strict rules on how to separate instructions in different lines. For example, instead of
of what our program is. int main ()
#include <iostream> {
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code cout << " Hello World!";
lines with expressions but indications for the compiler's preprocessor. In this case the directive return 0;
#include<iostream> tells the preprocessor to include the iostream standard file. This specific file }
(iostream) includes the declarations of the basic standard input-output library in C++, and it is
included because its functionality is going to be used later in the program. We could have written:
using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the int main ()
namespace with the name std. So in order to access its functionality we declare with this expression {
that we will be using these entities. This line is very frequent in C++ programs that use the standard cout << "Hello World!";
library, and in fact it will be included in most of the source codes included in these tutorials. return 0;
int main () }
This line corresponds to the beginning of the definition of the main function. The main function is All in just one line and this would have had exactly the same meaning as the previous code.
the point by where all C++ programs start their execution, independently of its location within the In C++, the separation between statements is specified with an ending semicolon (;) at the end of
source code. It does not matter whether there are other functions with other names defined before or each one, so the separation in different code lines does not matter at all for this purpose. We can
after it – the instructions contained within this function's definition will always be the first ones to be write many statements per line or write a single statement that takes many code lines. The division of
13 P.T.O 14 P.T.O
7
code in different lines serves only to make it more legible and schematic for the humans that may {
read it. char name[30];
int age;
Let us add an additional instruction to our first program: public:
// my second program in C++ void getdata(void);
#include <iostream> void display(void);
using namespace std; };
int main ()
{ void person :: getdata ( void )
cout << "Hello World! "; {
cout << "I'm a C++ program"; cout<<”enter name”;
return 0; cin>>name;
} cout<<”enter age”;
cin>>age;
Output:-Hello World! I'm a C++ program }
In this case, we performed two insertions into cout in two different statements. Once again, the void display()
separation in different lines of code has been done just to give greater readability to the program, {
since main could have been perfectly valid defined this way: cout<<”\n name:”<<name;
int main () cout<<”\n age:”<<age;
{ }
cout << " Hello World! ";
cout << " I'm a C++ program "; int main( )
return 0; {
}
person p;
We were also free to divide the code into more lines if we considered it more convenient: p.getdata();
int main () p.display();
{ return(0);
cout << "Hello World!";
cout << "I'm a C++ program"; }
return 0;
}
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not
statements. They are lines read and processed by the preprocessor and do not produce any code by
themselves. Preprocessor directives must be specified in their own line and do not have to end with a
semicolon (;).
Include files
Class declaration
Class functions, definition
Main function program
Example :-
# include<iostream.h>
class person
15 P.T.O 16 P.T.O
8
LECTURE-6 1. Only alphabetic chars, digits and under score are permitted.
2. The name can’t start with a digit.
TOKENS: 3. Upper case and lower case letters are distinct.
4. A declared keyword can’t be used as a variable name.
The smallest individual units in program are known as tokens. C++ has the following
tokens. In ANSI C the maximum length of a variable is 32 chars but in c++ there is no bar.
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
KEYWORDS:
The keywords implement specific C++ language feature. They are explicitly reserved
identifiers and can’t be used as names for the program variables or other user defined program
elements. The keywords not found in ANSI C are shown in red letter.
C++ KEYWORDS:
IDENTIFIERS:
Identifiers refers to the name of variable , functions, array, class etc. created by programmer. Each
language has its own rule for naming the identifiers.
17 P.T.O 18 P.T.O
9
Lecture-7 long int 4 -2147483648 to 2147483648
User defined type Built in types Derived type long double 10 3.4E-4932 to 1.1E+ 4932
Structure Array
Union Function
Class pointer
enumeration The type void normally used for:
1) To specify the return type of function when it is not returning any value.
2) To indicate an empty argument list to a function.
Integral type void Floating point
Example:
Void function(void);
int char float double Another interesting use of void is in the declaration of genetic pointer
Example:
Void *gp;
Both C and C++ compilers support all the built in types. With the exception of void the basic
datatypes may have several modifiers preceding them to serve the needs of various situations. The Assigning any pointer type to a void pointer without using a cast is allowed in both C and ANSI C.
modifiers signed, unsigned, long and short may applied to character and integer basic data types. In ANSI C we can also assign a void pointer to a non-void pointer without using a cast to non void
However the modifier long may also be applied to double. pointer type. This is not allowed in C ++.
Example:
Data types in C++ can be classified under various categories.
void *ptr1;
TYPE BYTES RANGE
void *ptr2;
char 1 -128 to – 127
Are valid statement in ANSI C but not in C++. We need to use a cast operator.
usigned 1 0 to 265
ptr2=(char * ) ptr1;
sgned char 1 -128 to 127
short int 2 -32768 to 32768 We have used user defined data types such as struct,and union in C. While these more features have
been added to make them suitable for object oriented programming. C++ also permits us to define
19 P.T.O 20 P.T.O
10
another user defined data type known as class which can be used just like any other basic data type to C++ also permits the creation of anonymous enums ( i.e, enums without tag names)
declare a variable. The class variables are known as objects, which are the central focus of oops.
Example:
ENUMERATED DATA TYPE:
enum{off,on};
An enumerated data type is another user defined type which provides a way for
attaching names to number, these by increasing comprehensibility of the code. The enum keyword Here off is 0 and on is 1.these constants may be referenced in the same manner as regular constants.
automatically enumerates a list of words by assigning them values 0,1,2 and soon. This facility
provides an alternative means for creating symbolic. Example:
enum colour{red,blue,green,yellow} ANSI C permits an enum defined with in a structure or a class, but the enum is
globally visible. In C++ an enum defined with in a class is local to that class.
enum position {off,on}
The enumerated data types differ slightly in C++ when compared with ANSI C. In C++, the
tag names shape, colour, and position become new type names. That means we can declare new
variables using the tag names.
Example:
ANSI C defines the types of enums to be ints. In C++,each enumerated data type retains its
own separate type. This means that C++ does not allow an int value to be automatically converted to
an enum.
Example:
Example:
By default, the enumerators are assigned integer values starting with 0 for the first
enumerator, 1 for the second and so on. We can also write
21 P.T.O 22 P.T.O
11
LECTURE-8 for(int i=1;i<5;i++)
{
cin>>x;
sum=sum+x
SYMBOLIC CONSTANT: }
float average;
There are two ways of creating symbolic constants in c++. average=sum/x;
cout<<average;
1. using the qualifier const. }
2. defining a set of integer constants using enum keywords.
In both C and C++, any value declared as const can’t be modified by the program in any way.
In C++, we can use const in a constant expression. Such as
REFERENCE VARIABLES:
C++interfaces a new kind of variable known as the reference variable. A references variable
provides an alias.(alternative name) for a previously defined variable. For example ,if we make the
const int size = 10 ; variable sum a reference to the variable total, then sum and total can be used interchangeably to represent
char name (size) ; the variuble.
A reference variable is created as follows:
Synatx: Datatype & reference –name=variable name;
Example:
This would be illegal in C. const allows us to create typed constants instead of having to use #defme to float total=1500;
create constants that have no type information. float &sum=total;
Here sum is the alternative name for variables total, both the variables refer to the same data object in the
const size=10; memory .
A reference variable must be initialized at the time of declaration .
Means Note that C++ assigns additional meaning to the symbol & here & is not an address operator
.The notation float & means reference to float.
const int size =10; Example:
int n[10];
C++ requires a const to be initialized. ANSI C does not require an initializer, if none is given, it
initializes the const to 0. int &x=n[10];
char &a=’\n’;
In C++ const values are local and in ANSI C const values are global .However they can be made local
made local by declaring them as static .In C++ if we want to make const value as global then declare as extern
storage class.
DECLARATION OF VARIABLES:
In ANSIC C all the variable which is to be used in programs must be declared at the beginning of the
program .But in C++ we can declare the variables any whose in the program where it requires .This makes the
program much easier to write and reduces the errors that may be caused by having to scan back and forth. It
also makes the program easier to understand because the variables are declared in the context of their use.
Example:
main( )
{
float x,average;
float sum=0;
23 P.T.O 24 P.T.O
12
LECTURE-9 In C,the global version of a variable can't be accessed from with in the inner block.
C++ resolves this problem by introducing a new operator :: called the scope resolution operator .This can be
used to uncover a hidden variable.
25 P.T.O 26 P.T.O
13
*q=7.5; LECTURE-10
Assign 25 to the newly created int object and 7.5 to the float object.We can also initialize the memory
using the new operator.
Syntax:
int *p=ne\v int(25); CONTROL STRUCTURES:
float *q =new float(7.5);
new can be used to create a memory space for any data type including user defined such as Like c,c++, supports all the basic control structures and implements them various control statements.
arrays,structures,and classes .The general form for a one-dimensional array is:
The if statement:
pointer-variable =new data types [size];
creates a memory space for an array of 10 integers. The if statement is impklemented in two forms:
If a data object is no longer needed, it is destroyed to release the memory space for reuse. 1. simple if statement
Example:
Simple if statement:
delete p;
delete q;
if (condition)
{
If we want to free a dynamically allocated array ,we must use the following
form of delete. Action;
MANIPULATERS: If (condition)
Manipulators are operator that are used to format the data display. The most commonly manipulators are Statment1
endl and setw.
The endl manipulator, when used in an output statement, causes a line feed to be insert.(just like \n) Else
Example:
cout<<”m=”<<m<<endl; Statement2
cout<<”n=”<<n<<endl;
cout<<”p=”<<p<<endl;
If we assume the values of the variables as 2597,14 and 175 respectively
m=2597; n=14;
p=175
It was want to print all nos in right justified way use setw which specify a common field width
for all the nos.
27 P.T.O 28 P.T.O
14
Switch(expr) The do-while statement:
{ Syn:
case 1: do
action1; {
break; Stements
case 2: } while(condition);
break; for(expression1;expression2;expression3)
.. {
.. Statements;
default: Statements;
message }
Syn:
While(condition)
Stements
29 P.T.O 30 P.T.O
15
LECTURE-11 2. for function s not returning values, if a return statement exists.
3. if functions contain static variables.
4. if inline functions are recursive,.
Example:
#include<iostream.h>
FUNCTION IN C++ :
#include<stdio.h>
inline float mul(float x, float y)
The main( ) Functon ; {
ANSI does not specify any return type for the main ( ) function which is the starting point for the execution return(x*y);
of a program . The definition of main( ) is :- }
inline double div(double p.double q)
main() {
{ return(p/q);
//main program statements }
}
This is property valid because the main () in ANSI C does not return any value. In C++, the main () returns a value of
type int to the operating system. The functions that have a return value should use the return statement for terminating. main( )
The main () function in C++ is therefore defined as follows. {
float a=12.345;
float b=9.82;
cout<<mul(a,b)<<endl;
cout<<div (a,b)<<endl;
int main( ) }
{
-------------- output:-
-------------- 121.227898
return(0) 1.257128
} DEFAULT ARGUMENT:-
Since the return type of functions is int by default, the key word int in the main( ) header is optional.
C++ allows us to call a function with out specifying all its arguments.In such cases, the
INLINE FUNCTION: function assigns a default value to the parameter which does not have a matching aguments in the
function call.Default values are specified when the function is declared .The compiler looks at the
To eliminate the cost of calls to small functions C++ proposes a new feature called inline function. prototype to see how many arguments a function uses and alerts the program for possible default
An inline function is a function that is expanded inline when it is invoked .That is the compiler values.
replaces the function call with the corresponding function code. Example: float amount (float principle, int period ,float rate=0.15);
The inline functions are defined as follows:- The default value is specified in a manner syntactically similar to a variable
initialization .The above prototype declares a default value of 0.15 to the argument rate. A
inline function-header subsequent function call like
{ value=amount(5000,7); //one argument missing
function body; passes the value of 5000 to principle and 7 to period and then lets the function, use default value of
} 0.15 for rate.
Example: inline double cube (double a) The call:- value=amount(5000,5,0.12);
{ //no missing argument passes an explicite value of 0.12 rate.
return(a*a*a); One important point to note is that only the trailing arguments can have default values. That is, we
} must add default from right to left .We cannot provide a default to a particular argument in the
The above inline function can be invoked by statements like middle of an argument list.
c=cube(3.0); Example:- int mul(int i, int j=5,int k=10);//illegal
d=cube(2.5+1.5); int mul(int i=0,int j,int k=10);//illegal
remember that the inline keyword merely sends a request, not a command to the compliler. The int mul(int i=5,int j);//illegal
compiler may ignore this request if the function definition is too long or too complicated and compile int mul(int i=2,int j=5,int k=10);//illegal
the function as a normal function. Default arguments are useful in situation whose some arguments always have the some value.
Some of the situations where inline expansion may not work are: For example,bank interest may retain the same for all customers for a particular period of deposit.
1. For functions returning values if a loop, a switch or a go to exists.
31 P.T.O 32 P.T.O
16
LECTURE-12
Example:
#include<iostream.h>
#include<stdio.h> FUNCTION OVERLOADING:
mainQ
{ Overloading refers to the use of the same thing for different purposes . C++ also
float amount; permits overloading functions .This means that we can use the same function name to creates
float value(float p,int n,float r=0.15); functions that perform a variety of different tasks. This is known as function polymorphism in oops.
void printline(char ch=’*’,int len=40); Using the concepts of function overloading , a family of functions with one function
printline( ); name but with different argument lists in the functions call .The correct function to be invoked is
amount=value(5000.00,5); determined by checking the number and type of the arguments but not on the function type.
cout<<”\n final value=”<<amount<<endl; For example an overloaded add() function handles different types of data as shown
printline(‘=’); below.
//function definitions //Declaration
float value (float p,int n, float r) int add(int a, int b); //prototype 1
{ int add (int a, int b, int c); //prototype 2
float si; double add(double x, double y); //prototype 3
si=(p*n*r)/100; double add(double p , double q); //prototype 4
return(si);
}
void printline (char ch,int len) //function call
{ cout<<add(5,10); //uses prototype 1
for(inti=l;i<=len;i++) cout<<add(15,10.0); //uses prototype 4
cout<<ch<<endl; cout<<add(12.5,7.5); //uses prototype 3
} cout<<add(5,10,15); //uses prototype 2
output:- cout<<add(0.75,5); //uses prototype 5
**************** A function call first matches the prototype having the same no and type of arguments and then calls
final value=10056.71613 the appropriate function for execution.
=============== The function selection invokes the following steps:-
Advantage of providing the default arguments are:
1. We can use default arguments to add new parameters to the existing functions. a) The compiler first tries to find an exact match in which the types of actual
2. Default argument s can be used to combine similar functions into one. arguments are the same and use that function .
b) If an exact match is not found the compiler uses the integral promotions to the actual
arguments such as :
char to int
CONST ARGUMENT:- float to double
In C++, an argument to a function can be declared as unit as const as shown to find a match
below. c)When either of them tails ,the compiler tries to use the built in conversions to the actual
int strlen(const char *p); arguments and them uses the function whose match is unique . If the conversion is possible to have
int length(const string &s); multiple matches, then the compiler will give error message.
The qualifier const tells the compiler that the function should not modify the argument .the Example:
compiler will generate an error when this condition is violated .This type of declaration is significant long square (long n);
only when we pass arguments by reference or pointers. double square(double x);
A function call such as :- square(lO)
Will cause an error because int argument can be converted to either long or
double .There by creating an ambiguous situation as to which version of square( )should be used.
33 P.T.O 34 P.T.O
17
PROGRAM Module-2:
#include<iostream.h> LECTURE-13
int volume(double,int);
double volume( double , int );
double volume(longint ,int ,int); CLASS:-
main( ) Class is a group of objects that share common properties and relationships .In C++, a class is
{ a new data type that contains member variables and member functions that operates on the variables.
cout<<volume(10)<<endl; A class is defined with the keyword class. It allows the data to be hidden, if necessary from external
cout<<volume(10)<<endl; cout<<volume(10)<<endl; use. When we defining a class, we are creating a new abstract data type that can be treated like any
} other built in data type.
int volume( ini s) Generally a class specification has two parts:-
{ a) Class declaration
return (s*s*s); //cube b) Class function definition
} the class declaration describes the type and scope of its members. The class function
double volume( double r, int h) definition describes how the class functions are implemented.
{
return(3.1416*r*r*h); //cylinder Syntax:-
} class class-name
long volume (longint 1, int b, int h) {
{ private:
return(1*b*h); //cylinder variable declarations;
} function declaration ;
public:
output:- 1000 variable declarations;
157.2595 function declaration;
112500 };
The members that have been declared as private can be accessed only
from with in the class. On the other hand , public members can be accessed from outside the class
also. The data hiding is the key feature of oops. The use of keywords private is optional by default,
the members of a class are private.
The variables declared inside the class are known as data members and the functions
are known as members mid the functions. Only the member functions can have access to the private
data members and private functions. However, the public members can be accessed from the outside
the class. The binding of data and functions together into a single class type variable is referred to as
encapsulation.
Syntax:-
class item
{
int member;
float cost;
public:
void getldata (int a ,float b);
void putdata (void);
The class item contains two data members and two function members, the data
members are private by default while both the functions are public by declaration. The function
getdata() can be used to assign values to the member variables member and cost, and putdata() for
displaying their values . These functions provide the only access to the data members from outside
the class.
35 P.T.O 36 P.T.O
18
LECTURE-14
CREATING OBJECTS:
Once a class has been declared we can create variables of that type
by using the class name. DEFINING MEMBER FUNCTION:
Example: Member can be defined in two places
item x; • Outside the class definition
creates a variables x of type item. In C++, the class variables are known as objects. Therefore • Inside the class function
x is called an object of type item.
37 P.T.O 38 P.T.O
19
cost=299.950012
INSIDE THE CLASS DEF1NATION: object -4
Another method of defining a member function is to replace the function declaration by the cost=175.5
actual function definition inside the class .
Example:
class item
{
Intnumber; Q.
float cost; Write a simple program using class in C++ to input subject mark and prints it.
public: ans:
void getdata (int a ,float b); class marks
void putdata(void) {
{ private :
cout<<number<<endl; cout<<cost<<endl; int ml,m2;
} public:
}; void getdata();
void displaydata();
A C++ PROGRAM WITH CLASS:
};
# include< iostream. h>
void marks: :getdata()
class item
{
{
cout<<”enter 1st subject mark:”;
int number;
cin>>ml;
float cost;
cout<<”enter 2nd subject mark:”;
public:
cin>>m2;
void getdata ( int a , float b);
}
void putdala ( void)
void marks: :displaydata()
{
{
cout<<“number:”<<number<<endl;
cout<<”Ist subject mark:”<<ml<<endl ;
cout<<”cost :”<<cost<<endl;
cout<<”2nd subject mark:”<<m2;
}
}
};
void main()
void item :: getdata (int a , float b)
{
{
clrscr();
number=a;
marks x;
cost=b;
x.getdata();
}
x.displaydata();
main ( )
{
}
item x;
cout<<”\nobjectx”<<endl;
x. getdata( 100,299.95);
x .putdata();
item y;
cout<<”\n object y”<<endl;
y. getdata(200,175.5);
y. putdata();
}
Output: object x
number 100
39 P.T.O 40 P.T.O
20
LECTURE-15
Private member functions:
NESTING OF MEMBER FUNCTION; Although it is a normal practice to place all the data items in a private section and all the functions in
public, some situations may require contain functions to be hidden from the outside calls. Tasks such
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. as deleting an account in a customer file or providing increment to and employee are events of
serious consequences and therefore the functions handling such tasks should have restricted access.
#include <iostream.h>
class set We can place these functions in the private section.
{
int m,n;
public:
void input(void); A private member function can only be called by another function that is a member of its class. Even
void display (void);
void largest(void); an object can not invoke a private function using the dot operator.
};
int set::largest (void)
{
if(m>n) Class sample
return m;
else {
return n; int m;
}
void set::input(void) void read (void);
{ void write (void);
cout<<”input values of m and n:”;
cin>>m>>n; };
} if si is an object of sample, then
void set::display(void)
{ s.read();
cout<<”largestvalue=”<<largest()<<”\n”; is illegal. How ever the function read() can be called by the function update ( ) to
}
void main() update the value of m.
{ void sample :: update(void)
set A;
A.input( ); {
A.display( ); read( );
}
}
output:
3017
largest value= 30
41 P.T.O 42 P.T.O
21
#include<iostream.h> #indude<iostream.h>
class distance
class part
{
{
private:
private:
int feet;
int modelnum,partnum;
float inches;
float cost;
public:
public:
void setdist ( int ft, float in)
void setpart ( int mn, int pn ,float c)
{
{
feet=ft;
modelmim=mn;
inches=in;
partnum=pn;
}
cost=e;
void getdist()
}
{
void showpart ( )
cout<<”enter feet:”;
{
Cout<<endl<<”model:”<<modelnum<<end1; cin>>feet;
Cout<<”num:”<< partnum <<endl cout<<”enter inches:”;
Cout<<”cost:”<<”$”<cost; cin>>inches;
} }
}; void showdist()
void main() {
{ cout<< feet<<”_”inches«endl;
part pl,p2; }
p1.setpart(644,73,217.55); };
p2.setpart(567,89,789.55); void main( )
pl.showpart(); {
pl.showpart(); distance dl,d2;
} d1.setdist(1 1,6.25);
d2.getdata();
output:- model:644 cout<<endl<<”dist:”<<d 1 .showdist();
cout<<”\n”<<”dist2:”;
num:73 d2.showdist();
cost: $217550003 }
43 P.T.O 44 P.T.O
22
LECTURE-16 employee emp[5]:
for( int i=0;i<5;i++)
ARRAY WITH CLASSES: {
emp[i].getdata();
#include<iostream.h> }
#include<conio.h> cout<<endl;
class employee for(i=0;i<5;i++)
{ {
private: emp[i].putdata();
char name[20]; }
int age,sal; getch();
public: return(0);
void getdata(); }
void putdata();
};
ARRAY OF OBJECTS:-
void employee : : getdata ()
#include<iostream.h>
{
#include<conio.h>
cout<<”enter name :”;
class emp
cin>>name;
{
cout<<”enter age :”;
private:
cin>>age;
char name[20];
cout<<”enter salary:”;
int age,sal;
cin>>sal;
public:
return(0);
void getdata( );
}
void putdata( );
void employee : : putdata ( )
};
{
void emp : : getdata( )
cout<<name <<endl;
{
cout<<age<<endl;
coul<<”enter empname”: .
cout<<sal<<endl;
cin>>name;
return(0);
cout<<”enter age:”<<endl;
}
cin>>age;
int main()
cout<<”enter salun :”;
{
45 P.T.O 46 P.T.O
23
cin>>sal;
REPLACE AND SORT USING CLASS:-
}
#include<iostream.h>
void emp :: putdata ()
#include<constream.h>
{
class sort
cout<<”emp name:”<<name<<endl;
{
cout<<”emp age:”<<age<<endl;
private:
cout<<”emp salary:”<<sal;
int nm[30];
}
public;
void getdata();
void putdata();
void main()
}:
{
void sort :: getdata()
emp foreman[5];
{
emp engineer[5];
int i,j,k;
for(int i=0;i<5;i ++)
cout<<”enter 10 nos:” ;
{
for(i=0;i<10;i++)
cout<<” for foreman:”;
{
foreman[i] . getdata();
cin>>nm[i];
}
}
cout<<endl;
for(i=0;i<9;i++)
for(i=0;i<5;i++)
{
{
for(j=i+l:j<10:j++)
Foreman[i].putdata(); .
{
}
if(nm[i]>nm[j])
for(int i=0;i<5;i ++)
{
{
k=nm[i];
cout<<” for engineer:”;
nm[i]=nm[j];
ingineer[i].getdata();
nm[j]=k;
}
}
for(i=0;i<5;i++)
}
{
ingineer[i].putdata();
void sort :: putdata()
}
{
getch(); int k;
for(k=0;k<10;k++)
return(0);
{
} cout<<num [k] <<endl ;
47 P.T.O 48 P.T.O
24
} sum=sum+item_price[i];
} }
int main() cout<< “\n total value:”<<sum<<endl;
{ }
clrscr(); int main ( )
sort s; {
s.getdata(); items order;
s.putdata(); order.cnt();
return(0); int x;
} do
ARRAY OF MEMBERS: {
cout<<”\nyou can do the following:”;
#include<iostream.h>
cout<<”enter appropriate no:”;
#include<constream.h> cout<<endl<<” 1 :add an item’’;
cout<<endl<<”2: display total value :”;
const int m=50;
cout<<endl<<”3 : display an item”;
class items cout<<endl<<”4 :display all item:”;
cout<<endl<<”5 : quit:”;
{
cout<<endl<<endl<<”what is your option:”;
int item_code[m]; cin>>x;
float item_price[m];
switch(x)
int count; {
case 1: order.get_item(); break;
public:
case 2: order.display_sum(); break;
void cnt(void) { count=0;} cose 3: order.remove(); break;
case 4: order.display_item();break;
void get_item(void);
case 5: break;
void display_sum(void); default : cout<<”error in input; try again”;
}
void remove(void);
} while(x!=5);
void display _item(void); }
};
49 P.T.O 50 P.T.O
25
c.getdata( );
LECTURE-17 cout«"after reading data : "«endl;
a.get_count( );
b.gel_count( );
c.get count( );
STATIC DATA MEMBER: return(0);
}
A data member of a class can be qualified as static . The
properties of a static member variable are similar to that of a static variable. A static member variable The output would be
has contain special characteristics. count:0
Variable has contain special characteristics:- count:0
1) It is initialized to zero when the first object of its class is created.No other count:0
initialization is permitted. After reading data
2) Only one copy of that member is created for the entire class and is shared by count: 3
all the objects of that class, no matter how many objects are created. count:3
3) It is visible only with in the class but its life time is the entire program. Static count:3
variables are normally used to maintain values common to the entire class.
For example a static data member can be used as a counter that records the
occurrence of all the objects.
int item :: count; // definition of static data member The static Variable count is initialized to Zero when the objects created . The count is
incremented whenever the data is read into an object. Since the data is read into objects three times
the variable count is incremented three times. Because there is only one copy of count shared by all
Note that the type and scope of each static member variable must be defined outside the three object, all the three output statements cause the value 3 to be displayed.
the class definition .This is necessary because the static data members are stored separately rather
than as a part of an object. STATIC MEMBER FUNCTIONS:-
Example :-
#include<iostream.h> A member function that is declared static has following properties :-
class item 1. A static function can have access to only other static members declared in the
{ same class.
static int count; //count is static 2. A static member function can be called using the class name as follows:-
int number; class - name :: function - name;
public: Example:-
void getdata(int a) #include<iostream.h>
. { class test
number=a; {
count++; int code;
} static int count; // static member variable
void getcount(void) public:
{ void set(void)
cout<<”count:”; {
cout<<count<<endl; code=++count;
} }
}; void showcode(void)
int item :: count ; //count defined {
int main( ) cout<<”object member : “<<code<<end;
{ }
item a,b,c; static void showcount(void)
a.get_count( ); { cout<<”count=”<<count<<endl; }
b.get_count( ); };
c.get_count( ): int test:: count;
a.getdata( ): int main()
b.getdata( ); {
51 P.T.O 52 P.T.O
26
test t1,t2; void sum( time ,time);
t1.setcode( ); };
t2.setcode( ); void time :: sum (time t1,time t2) .
test :: showcount ( ); ' {
test t3; minutes=t1.minutes + t2.minutes;
t3.setcode( ); hours=minutes%60;
test:: showcount( ); minutes=minutes%60;
t1.showcode( ) ; hours=hours+t 1.hours+t2.hours;
t2.showcode( ); }
t3.showcode( );
return(0); int main()
{
time T1,T2,T3;
T1.gettime(2,45);
T2.gettime(3,30);
output:- count : 2 T3.sum(T1,T2);
count: 3 cout<<”T1=”;
object number 1 T1.puttime( );
object number 2 cout<<”T2=”;
object number 3 T2.puttime( );
cout<<”T3=”;
T3.puttime( );
OBJECTS AS FUNCTION ARGUMENTS return(0);
}
Like any other data type, an object may be used as A function argument. This can cone in two ways
1. A copy of the entire object is passed to the function.
2. Only the address of the object is transferred to the function
The first method is called pass-by-value. Since a copy of the object is passed to the function, any
change made to the object inside the function do not effect the object used to call the function.
The second method is called pass-by-reference . When an address of the object is passed, the called
function works directly on the actual object used in the call. This means that any changes made to the
object inside the functions will reflect in the actual object .The pass by reference method is more
efficient since it requires to pass only the address of the object and not the entire object.
Example:-
#include<iostream.h>
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime(void)
{
cout<< hours<<”hours and:”;
cout<<minutes<<”minutes:”<<end;
}
53 P.T.O 54 P.T.O
27
LECTURE-18 sample x;
x . setvalue( );
cout<<”mean value=”<<mean(x)<<endl;
FRIENDLY FUNCTIONS:- return(0);
We know private members can not be accessed from outside the class. That is a non -
member function can't have an access to the private data of a class. However there could be a case }
where two classes manager and scientist, have been defined we should like to use a function income-
tax to operate on the objects of both these classes. output:
In such situations, c++ allows the common function lo be made friendly with both the classes , there mean value : 32.5
by following 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. A function friendly to two classes
To make an outside function "friendly" to a class, we have to simply declare this function as a friend #include<iostream.h>
of the classes as shown below : class abc;
class xyz
class ABC {
{ int x;
--------- public:
--------- void setvalue(int x) { x-= I; }
public: friend void max (xyz,abc);
-------- };
---------- class abc
friend void xyz(void); {
}; int a;
public:
The function declaration should be preceded by the keyword friend , The function is defined else void setvalue( int i) {a=i; }
where in the program like a normal C ++ function . The function definition does not use their the friend void max(xyz,abc);
keyword friend or the scope operator :: . The functions that are declared with the keyword friend are };
known as friend functions. A function can be declared as a friend in any no of classes. A friend
function, as though not a member function , has full access rights to the private members of the class.
void max( xyz m, abc n)
A friend function processes certain special characteristics: {
a. It is not in the scope of the class to which it has been declared as friend. if(m . x >= n.a)
b. Since it is not in the scope of the class, it cannot be called using the object of that cout<<m.x;
class. It can be invoked like a member function without the help of any object. else
c. Unlike member functions. cout<< n.a;
}
Example:
int main( )
#include<iostream.h> {
class sample abc j;
{ j . setvalue( 10);
int a; xyz s;
int b; s.setvalue(20);
public: max( s , j );
void setvalue( ) { a=25;b=40;} return(0);
friend float mean( sample s); }
} SWAPPING PRIVATE DATA OF CLASSES:
float mean (sample s)
{ #include<iostream.h>
return (float(s.a+s.b)/2.0);
} class class-2;
int main ( ) class class-1
{ {
55 P.T.O 56 P.T.O
28
int value 1; PROGRAM FOR ILLUSTRATING THE USE OF FRIEND FUNCTION:
public:
void indata( int a) { value=a; } #include< iostream.h>
void display(void) { cout<<value<<endl; } class account1;
friend void exchange ( class-1 &, class-2 &); class account2
}; {
private:
class class-2 int balance;
{ public:
int value2; account2( ) { balance=567; }
public: void showacc2( )
void indata( int a) { value2=a; } {
void display(void) { cout<<value2<<endl; } cout<<”balanceinaccount2 is:”<<balance<<endl;
friend void exchange(class-l & , class-2 &); friend int transfer (account2 &acc2, account1 &acc1,int amount);
}; };
void exchange ( class-1 &x, class-2 &y) class acount1
{ {
int temp=x. value 1; private:
x. value I=y.valuo2; int balance;
y.value2=temp; public:
} account1 ( ) { balance=345; }
int main( )
{ void showacc1 ( )
class-1 c1; {
class-2 c2; cout<<”balance in account1 :”<<balance<<endl;
c1.indata(l00); }
c2.indata(200); friend int transfer (account2 &acc2, account1 &acc1 ,int amount);
cout<<”values before exchange:”<<endl; };
c1.display( );
c2.display( ); int transfer ( account2 &acc2, account1 & acc1, int amount)
exchange (c1,c2); {
cout<<”values after exchange :”<< endl; if(amount <=accl . bvalance)
c1. display ( ); {
c2. display ( ); acc2. balance + = amount;
return(0); acc1 .balance - = amount;
} }
output: else
values before exchange return(0);
100 }
200 int main()
values after exchange {
200 account1 aa;
100 account2 bb;
57 P.T.O 58 P.T.O
29
cout<< “ balance in the accounts after the transfer:”;
aa . showacc 1 ( ); LECTURE-19
bb. showacc 2( );
return(0);
}
output: RETURNING OBJECTS:
balance in the accounts before transfer # include< iostream,h>
balance in account 1 is 345 class complex
balance in account2 is 567 {
and transferred from account! to account2 is 100 float x;
balance in account 1 is 245 float y;
balance in account2 is 667 public:
void input( float real , float imag)
{
x=real;
y=imag;
}
friend complex sum( complex , complex);
void show ( complex );
};
complex sum ( complex c1, complex c2)
{
complex c3;
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return c3;}
int main( )
{
complex a, b,c;
a.input(3.1,5.65);
b.input(2.75,1.2);
c=sum(a,b);
cout <<” a=”; a.show(a);
cout <<” b= “; b.show(b);
cout <<” c=” ; c.show(c);
return(0);
}
output:
a =3.1 + j 5.65
b= 2.75+ j 1.2
c= 5.55 + j 6.85
59 P.T.O 60 P.T.O
30
POINTER TO MEMBERS; DEREFERENCING OPERATOR:
It is possible to take the address of a member of a class and assign it to a pointer. The address #include<iostream.h>
of a member can be obtained by applying the operator & to a “fully qualified” class member name. class M
{
A class member pointer can be declared using the operator :: * with the class name. int x;
For Example: int y;
class A public:
{ void set_xy(int a,int b)
private: {
int m; x=a;
public: y=b;
void show( ); }
}; friend int sum(M);
We can define a pointer to the member m as follows : };
int A :: * ip = & A :: m
The ip pointer created thus acts like a class member in that it must be invoked with a class object. In int sum (M m)
the above statement. The phrase A :: * means “pointer - to - member of a class” . The phrase & A :: {
m means the “ Address of the m member of a class” int M :: * px= &M :: x; //pointer to member x
61 P.T.O 62 P.T.O
31
the base class constructor .
LECTURE-20 Like other C++ function , they can have default arguments,
Constructor can't be virtual.
An object with a constructor can't be used as a member of
union.
CONSTRUCTOR: Example of default constructor:
A constructor is a special member function whose task is to initialize the objects of its class .
It is special because its name is the same as the class name. The constructor is invoked when ever an #include<iostream.h>
object of its associated class is created. It is called constructor because it construct the values of data #include<conio.h>
members of the class.
class abc
A constructor is declared and defined as follows: {
//'class with a constructor private:
class integer char nm[];
{ public:
int m,n: abc ( )
public: {
integer! void);//constructor declared cout<<”enter your name:”;
------------ cin>>nm;
------------ }
}; void display( )
integer :: integer(void)
{
m=0;
n=0;
}
{
cout<<nm;
}
When a class contains a constructor like the one defined above it is guaranteed that an
object created by the class will be initialized automatically. };
32
integer:: integer (int x, int y) Example:-
{ #include<iostream.h>
m=x;n=y; #include<conio.h>
} class abc
the argument can be passed to the constructor by calling the constructor {
implicitly. private:
integer int 1 = integer(0,100); // explicit call char nm [30];
integer int 1(0,100); //implicite call int age;
public:
CLASS WITH CONSTRUCTOR:- abc ( ){ }// default
abc ( char x[], int y);
void get( )
#include<iostream.h> {
class integer cout<<”enter your name:”;
{ cin>>nm;
int m,n; cout<<” enter your age:”;
public: cin>>age;
integer(int,int); }
void display(void) void display( )
{
cout<<nm«endl;
cout«age;
}
{ };
cout<<”m=:”<<m ; abc : : abc(char x[], int y)
cout<<”n=”<<n; {
} strcpy(nm,x);
}; age=y;
integer :: integer( int x,int y) // constructor defined }
{ void main( )
m=x; {
n=y; abc 1;
} abc m=abc("computer",20000);
int main( ) l.get();
{ l.dispalay( );
integer int 1(0, 100); // implicit call m.display ( );
integer int2=integer(25,75); getch( );
cout<<” \nobjectl “<<endl; }
int1.display( );
cout<<” \n object2 “<<endl;
int2.display( ); OVERLOADED CONSTRUCTOR:-
} #include<iostream.h>
output: #include<conio.h>
object 1 class sum
m=0 {
n=100 private;
object2 int a;
m=25 int b;
n=25 int c;
float d;
double e;
public:
sum ( )
65 P.T.O
33
{
cout<<”enter a;”; public
cin>>a; code ( ) { } //constructor
cout<<”enter b;”; code (int a) { id=a; } //constructor
cin>>b; code(code &x)
cout<<”sum= “<<a+b<<endl; {
} Id=x.id;
sum(int a,int b); }
sum(int a, float d,double c); void display( )
}; {
sum :: sum(int x,int y) cout<<id;
{ }
a=x; };
b=y; int main( )
} {
sum :: sum(int p, float q ,double r) code A(100);
{ code B(A);
a=p; code C=A;
d=q; code D;
e=r; D=A;
} cout<<” \n id of A :”; A.display( );
void main( ) cout<<” \nid of B :”; B.display( );
{ cout<<” \n id of C:”; C.display( );
clrscr( ); cout<<” \n id of D:”; D.display( );
sum 1; }
sum m=sum(20,50);
sum n= sum(3,3.2,4.55);
getch( ); output :-
} id of A:100
id of B:100
output: id of C:100
enter a : 3 id of D:100
enter b : 8
sum=11
sum=70 DYNAMIC CONSTRUCTOR:-
sum=10.75 The constructors can also be used to allocate memory while creating objects .
This will enable the system to allocate the right amount of memory for each object when the objects
are not of the same size, thus resulting in the saving of memory.
COPY CONSTRUCTOR: Allocate of memory to objects at the time of their construction is known as dynamic
A copy constructor is used to declare and initialize an object from another object. constructors of objects. The memory is allocated with the help of new operator.
Example:- Example:-
the statement #include<iostream.h>
integer 12(11); #include<string.h>
would define the object 12 and at the same time initialize it to the values of 11. class string
Another form of this statement is : integer 12=11; {
The process of initialization through a copy constructor is known as copy initialization. char *name;
Example:-
#incliide<iostream.h>
class code
{
int id; int length;
public:
string ( )
34
{ LECTURE-21
length=0;
name= new char [length+1]; /* one extra for \0 */
}
string( char *s) //constructor 2 DESTRUCTOR:-
{
length=strlen(s); A destructor, us the name implies is used to destroy the objects that have been created by a
name=new char [length+1]; constructor. Like a constructor, the destructor is a member function whose name is the same as the
strcpy(name,s); class name but is preceded by a tilde.
}
void display(void) For Example:-
{ ~ integer( ) { }
cout<<name<<endl; A destructor never takes any argument nor does it return any value. It will be invoked
} implicitly by the compiler upon exit from the program to clean up storage that is no longer
void join(string &a .string &b) accessible. It is a good practice to declare destructor in a program since it releases memory space for
{ future use.
length=a. length +b . length; Delete is used to free memory which is created by new.
delete name; Example:-
name=new char[length+l]; /* dynamic allocation */ matrix : : ~ matrix( )
strcpy(name,a.name); {
strcat(name,b.name); for(int i=0; i<11;i++)
} delete p[i];
}; delete p;
int main( ) }
{
char * first = “Joseph” ;
string name1(first),name2(“louis”),naine3( “LaGrange”),sl,s2; IMPLEMENTED OF DESTRUCTORS:-
sl.join(name1,name2); #include<iostream.h>
s2.join(s1,name3); int count=0;
namel.display( ); class alpha
name2.display( ); {
name3.display( ); public:
s1.display( ); alpha( )
s2.display( ); {
} count ++;
output :- cout<<”\n no of object created :”<<endl;
Joseph }
Louis ~alpha( )
language {
Joseph Louis cout<<”\n no of object destroyed :” <<endl;
Joseph Louis Language coutnt--;
}
};
int main( )
{
35
alpha A5; LECTURE-22 & 23
}
{
cout<<” \n \n enter block2 \n”; OPERATOR OVERLOADING:-
alpha A6; Operator overloading provides a flexible option for the creation of new definations for most
} of the C++ operators. We can overload all the C++ operators except the following:
cout<<\n re-enter main \n:”;
return(0); Class members access operator (. , .*)
} Scope resolution operator (: :)
Size operator(sizeof)
output:- Condition operator (? :)
enter main Although the semantics of an operator can be extended, we can't change its syntax, the
no of object created 1 grammatical rules that govern its use such as the no of operands precedence and associativety. For
no of object created 2 example the multiplication operator will enjoy higher precedence than the addition operator.
no of object created 3 When an operator is overloaded, its original meaning is not lost. For example,
no of object created 4 the operator +, which has been overloaded to add two vectors, can still be used to add two integers.
enter block 1
no of object created 5 DEFINING OPERATOR OVERLOADING:
no of object destroyed 5 To define an additional task to an operator, we must specify what it means in
enter block 2 relation to the class to which the operator is applied . This is done with the help of a special function
no of object created 5 called operator function, which describes the task.
no of object destroyed 5 Syntax:-
re-enter main return-type class-name :: operator op( arg-list)
no of object destroyed 4 {
no of object created 3 function body
no of object created 2 }
no of object created 1 Where return type is the type of value returned by the specified operation and
op is the operator being overloaded. The op is preceded by the keyword operator, operator op is the
Example :- function name.
#include<iostream.h> operator functions must be either member function, or friend
int x=l; function. A basic defference between them is that a friend function will have only one argument for
class abc unary operators and two for binary operators, This is because the object used to invoke the member
{ function is passed implicitly and therefore is available for the member functions. Arguments may be
public: either by value or by reference.
abc( )
{ operator functions are declared in. the class using prototypes as follows:-
x--; vector operator + (vector); /./ vector addition
cout<<”construct the no”<<x<<endl; vector operator-( ); //unary minus
} friend vector operator + (vuelor, vector); // vector add
~abc( ) friend vector operator -(vector); // unary minus
{ vector operator - ( vector &a); // substraction
cout<<”destruct the no:”<<x<<endl; int operator = =(vector); //comparision
x--; friend int operator = =(vector ,vrctor); // comparision
} vector is a data type of class and may represent both magnitude and direction or a series
}; of points called elements.
int main( ) The process of overloading involves the following steps:-
{ 1. Create a class that defines the data type that is used in the overloading operation.
abc I1,I2,I3,I4;
cout«ll«12«13«l4«endl; 2. Declare the operator function operator op() in the public part of the class
return(0); 3. It may be either a member function or friend function.
}
4. Define the operator function to implement the required operations.
36
Overloaded operator functions can be invoked by expressions such as x.show();
op x or x op; }
for unary operators and
x op y Unary – - operator overloading(using friend function):
for binary opearators.
class abc
operator op(x);
{
for unary operator using friend function
int m,n;
operator op(x,y);
public:
for binary operator usinf friend function.
abc()
{
37
Unary operator+ for adding two complex numbers (using member function) }
void show()
class complex {
{ cout<<real<<”+i”<<img;
float real,img; }
public: friend complex operator+(complex &p,complex &q);
complex() };
{ complex operator+(complex &p,complex &q)
real=0; {
img=0; complex w;
} w.real=p.real+q.real;
complex(float r,float i) w.img=p.img+q.img;
{ return w;
real=r; }
img=i; };
} void main()
void show() {
{ complex s(3,4);complex t(4,5);
cout<<real<<”+i”<<img; complex m;
} m=operator+(s,t);
complex operator+(complex &p) s.show();t.show();
{ m.show();
complex w; }
w.real=real+q.real;
w.img=img+q.img;
return w; Overloading an operator does not change its basic meaning. For example assume the +
} operator can be overloaded to subtract two objects. But the code becomes unreachable.
}; class integer
void main() {
{ intx, y;
complex s(3,4); public:
complex t(4,5); int operator + ( ) ;
complex m; }
m=s+t; int integer: : operator + ( )
s.show(); {
t.show(); return (x-y) ;
m.show(); }
} Unary operators, overloaded by means of a member function, take no explicit argument and
Unary operator+ for adding two complex numbers (using friend function) return no explicit values. But, those overloaded by means of a friend function take one
reference argument (the object of the relevant class).
class complex Binary operators overloaded through a member function take one explicit argument and those
{ which are overloaded through a friend function take two explicit arguments.
float real,img;
public: Table 7.2
complex() Operator to Arguments passed to the Arguments passed to the Friend
{ Overload Member Function Function
real=0; Unary Operator No 1
img=0; Binary Operator 1 2
}
complex(float r,float i)
{
real=r;
img=i;
38
LECTURE-24 The program statement
si = string (namel);
Type Conversions
first converts name 1 from char* type to string type and then assigns the string type values to the
In a mixed expression constants and variables are of different data types. The assignment operations object s1. The statement
causes automatic type conversion between the operand as per certain rules.
s2 = name2;
The type of data to the right of an assignment operator is automatically converted to the data type of
variable on the left. performs the same job by invoking the constructor implicitly.
Consider the following example
Consider the following example: class time
int x; {
float y = 20.123; int hours;
x=y ; int minutes;
public:
This converts float variable y to an integer before its value assigned to x. The type conversion is time (int t) // constructor
automatic as far as data types involved are built in types. We can also use the assignment operator in {
case of objects to copy values of all data members of right hand object to the object on left hand. The hours = t / 60; //t is inputted in minutes
objects in this case are of same data type. But of objects are of different data types we must apply minutes = t % 60;
conversion rules for assignment. }
};
There are three types of situations that arise where data conversion are between incompatible types.
1. Conversion from built in type to class type. In the following conversion statements :
2. Conversion from class type to built in type.
3. Conversion from one class type to another. time Tl; //object Tl created
int period = 160;
Basic to Class Type Tl = period; //int to class type
The object Tl is created. The variable period of data type integer is converted into class type time by
A constructor was used to build a matrix object from an int type array. Similarly, we used another invoking the constructor. After this conversion, the data member hours ofTl will have value 2 arid
constructor to build a string type object from a char* type variable. In these examples constructors minutes will have a value of 40 denoting 2 hours and 40 minutes.
performed a defacto type conversion from the argument's type to the constructor's class type
Note that the constructors used for the type conversion take a single argument whose type is to be
Consider the following constructor: converted.
string :: string (char*a) In both the examples, the left-hand operand of = operator is always a class object. Hence, we can
{ also accomplish this conversion using an overloaded = operator.
length = strlen (a);
name=new char[len+1];
strcpy (name,a);
}
This constructor builds a string type object from a char* type variable a. The variables length and
name are data members of the class string. Once you define the
constructor in the class string, it can be used for conversion from char* type to string type.
Example
string si , s2;
char* namel = “Good Morning”;
char* name2 = “ STUDENTS” ;
s1 = string(namel);
s2 = name2;
39
LECTURE-25 Converts the class object of which it is a member to typename. The type name may be a built-in type
or a user defined one(another class type) . In the case of conversions between objects,
Class to Basic Type typename refers to the destination class. Therefore, when a class needs to be converted, a
casting operator function can be used. The conversion takes place in the source class and the result is
The constructor functions do not support conversion from a class to basic type. C++ allows us to
given to the destination class object.
define a overloaded casting operator that convert a class type data to basic type. The general form of
Let us consider a single-argument constructor function which serves as an instruction for
an overloaded casting operator function, also referred to as a conversion function, is:
converting the argument's type to the class type of which it is a member. The argument belongs to
operator typename ( )
the source class and is passed to the destination class for conversion. Therefore the conversion
{
constructor must be placed in the destination class.
//Program statmerit .
Table 7.3
}
Conversion Conversion takes place in
This function converts a class type data to typename. For example, the operator double( ) converts a
Source class Destination class
class object to type double, in the following conversion function:
Basic to class Not applicable Constructor
vector:: operator double ( )
Class to Basic Casting operator Not applicable
{
Class to class Casting operator Constructor
double sum = 0 ;
for(int I = 0; ioize;
When a conversion using a constructor is performed in the destination class, we must be able to
sum = sum + v[i] * v[i ] ; //scalar magnitude
access the data members of the object sent (by the source class) as an argument. Since data members
return sqrt(sum);
of the source class are private, we must use special access functions in the source class to facilitate
}
its data flow to the destination class.
The casting operator should satisfy the following conditions.
Consider the following example of an inventory of products in a store. One way of keeping record of
It must be a class member.
the details of the products is to record their code number, total items in the stock and the cost of each
It must not specify a return type. item. Alternatively we could just specify the item code and the value of the item in the stock. The
It must not have any arguments. Since it is a member function, it is invoked following program uses classes and shows how to convert data of one type to another.
by the object and therefore, the values used for, Conversion inside the
function belongs to the object that invoked the function. As a result function #include<iostream.h>
does not need an argument. #include<conio.h>
class stock2;
In the string example discussed earlier, we can convert the object string to char* as follows: class stock1
string:: operator char*( ) {
{ int code, item;
return (str) ; float price;
} public:
stockl (int a, int b, float c)
One Class to Another Class Type {
code=a;
We have just seen data conversion techniques from a basic to class type and a class to basic type. But item=b;
sometimes we would like to convert one class data type to another class type. price=c;
}
Example void disp( )
Obj1 = Obj2 ; //Obj1 and Obj2 are objects of different classes. {
Objl is an object of class one and Obj2 is an object of class two. The class two type data is converted cout<<”code”<<code <<”\n”;
to class one type data and the converted value is assigned to the Objl. Since the conversion takes cout<<”Items”<<item <<”\n”;
place from class two to class one, two is known as the source and one is known as the destination cout<<”Price per item Rs . “<<price <<”\n”;
class. }
Such conversion between objects of different classes can be carried out by either a int getcode( )
constructor or a conversion function. Which form to use, depends upon where we want the type- {return code; }
conversion function to be located, whether in the source class or in the destination class. int getitem( )
We studied that the casting operator function {return item; }
Operator typename( ) int getprice( )
{return price;}
40
operator float( ) Price per item Rs. 125
{
Stock value
return ( item*price );
} 1250
};
void main ( )
{ '
Stockl il(101, 10,125.0);
Stock2 12;
float tot_val;
tot_val=i1 ;
i2=il ;
cout<<” Stock Details-stockl-type” <<”\n”;
i 1 . disp ( ) ;
cout<<” Stock value”<<”\n”;
cout<< tot_val<<”\n”;
cout<<” Stock Details-stock2-type”<< “\n”;
i2 .disp( ) ;
getch ( ) ;
}
41
LECTURE-26 int age;
char name [10];
Inheritance: public:
void get ( );
};
Reaccessability is yet another feature of OOP's. C++ strongly supports the concept of reusability.
void worker : : get ( )
The C++ classes can be used again in several ways. Once a class has been written and tested, it can
{
be adopted by another programmers. This is basically created by defining the new classes, reusing
cout <<”yout name please”
the properties of existing ones. The mechanism of deriving a new class from an old one is called
cin >> name;
'INHERTTENCE'. This is often referred to as IS-A' relationship because very object of the class
cout <<”your age please” ;
being defined "is" also an object of inherited class. The old class is called 'BASE' class and the new
cin >> age;
one is called'DERIEVED'class.
}
void worker :: show ( )
Defining Derived Classes {
A derived class is specified by defining its relationship with the base class in addition to its own cout <<”In My name is :”<<name<<”In My age is :”<<age;
details. The general syntax of defining a derived class is as follows: }
class manager :: public worker //derived class (publicly)
class d_classname : Access specifier baseclass name {
{ int now;
__ public:
__ // members of derived class void get ( ) ;
}; void show ( ) ;
};
The colon indicates that the a-class name is derived from the base class name. The access specifier or void manager : : get ( )
the visibility mode is optional and, if present, may be public, private or protected. By default it is {
private. Visibility mode describes the status of derived features e.g. worker : : get ( ) ; //the calling of base class input fn.
cout << “number of workers under you”;
class xyz //base class cin >> now;
{ cin>>name>>age;
members of xyz } ( if they were public )
}; void manager :: show ( )
class ABC : public xyz //public derivation {
{ worker :: show ( ); //calling of base class o/p fn.
members of ABC cout <<“in No. of workers under me are: “ << now;
}; }
class ABC : XYZ //private derivation (by default) main ( )
{ {
members of ABC clrscr ( ) ;
}; worker W1;
In the inheritance, some of the base class data elements and member functions are inherited into the manager M1;
derived class. We can add our own data and member functions and thus extend the functionality of M1 .get ( );
the base class. Inheritance, when used to modify and extend the capabilities of the existing classes, M1.show ( ) ;
becomes a very powerful tool for incremental program development. }
If you input the following to this program:
Single Inheritance Your name please
When a class inherits from a single base class, it is known as single inheritance. Following program Ravinder
shows the single inheritance using public derivation. Your age please
#include<iostream.h> 27
#include<conio.h> number of workers under you
class worker
{ 30
42
clrscr ( ) ;
worker wl ;
manager ml;
Then the output will be as follows:
ml.get ( ) ;
My name is : Ravinder ml.show ( );
}
My age is : 27
The following program shows the single inheritance using protected derivation
No. of workers under me are : 30
#include<conio.h>
The following program shows the single inheritance by private derivation. #include<iostream.h>
class worker //Base class declaration
#include<iostream.h>
{ protected:
#include<conio.h> int age; char name [20];
public:
class worker //Base class declaration
void get ( );
{ void show ( );
int age; };
char name [10] ; void worker :: get ( )
public: {
void get ( ) ; cout >> “your name please”;
void show ( ) ; cin >> name;
}; cout << “your age please”;
void worker : : get ( ) cin >> age;
{ }
cout << “your name please” ; void worker :: show ( )
cin >> name; {
cout << “your age please”; cout << “in my name is: “ << name << “in my age is “ <<age;
cin >>age; }
} class manager:: protected worker // protected inheritance
void worker : show ( ) {
{ int now;
cout << “in my name is: “ <<name<< “in” << “my age is : “ <<age; public:
} void get ( );
class manager : worker //Derived class (privately by default) void show ( ) ;
{ };
int now; void manager : : get ( )
public: {
void get ( ) ; cout << “please enter the name In”;
void show ( ) ; cin >> name;
}; cout<< “please enter the age In”; //Directly inputting the data
void manager : : get ( ) cin >> age; members of base class
{ cout << “ please enter the no. of workers under you:”;
worker : : get ( ); //calling the get function of base cin >> now;
cout << “number of worker under you”; class which is }
cin >> now; void manager : : show ( )
}
void manager : : show ( ) {
{ cout « "your name is : "«name«" and age is : "«age;
worker : : show ( ) ; cout «"In no. of workers under your are : "«now;
cout << “in no. of worker under me are : “ <<now; main ( )
} {
main ( ) clrscr ( ) ;
{ manager ml;
ml.get ( ) ;
43
cout « "\n \n";
ml.show ( );
LECTURE-27
}
#include<iostream.h>
#include<conio.h>
class worker // Base class declaration
{
int age;
char name [20] ;
public;
void get( ) ;
44
void show( ) ;
}
main ( )
{
void worker: get ( ) clrscr ( ) ;
{ ceo cl ;
cout << “your name please” ; cl.get ( ) ; cout << “\n\n”;
cin >> name; cl.show ( ) ;
cout << “your age please” ; }
} Worker
void worker : : show ( )
Private:
{
int age;
cout << “In my name is : “ <<name<< “ In my age is : “ <<age;
char name[20];
}
class manager : public worker //Intermediate base class derived
Protected:
{ //publicly from the base class
int now;
Private:
public:
int age;
void get ( ) ;
char name[20];
void show( ) ;
};
void manager :: get ( ) Manager:Worker
{
worker : :get () ; //calling get ( ) fn. of base class Private:
cout << “no. of workers under you:”; int now;
cin >> now;
} Protected:
void manager : : show ( )
{ Public:
worker : : show ( ) ; //calling show ( ) fn. of base class void get()
cout << “In no. of workers under me are: “<< now; void show()
} worker ::get()
worker ::get()
class ceo: public manager //declaration of derived class
{ //publicly inherited from the
int nom; //intermediate base class
Ceo: Manager
public:
void get ( ) ;
Public:
void show ( ) ;
};
Protected:
void ceo : : get ( )
{ Public:
manager : : get ( ) ; All the inherited
cout << “no. of managers under you are:”; cin >> nom; members
}
void manager : : show ( )
{
cout << “In the no. of managers under me are: In”;
cout << “nom;
}
45
Multiple Inheritances
A class can inherit the attributes of two or more classes. This mechanism is known as ‘MULTIPLE public:
INHERITENCE’. Multiple inheritance allows us to combine the features void get ( )
{
of several existing classes as a starring point for defining new classes. It is like the child inheriting cout << “mother’s name please” << “In”;
the physical feature of one parent and the intelligence of another. The syntax of the derived class is cin >> name;
as follows: cout << “mother’s age please” << “in”;
cin >> age;
Class base1 Class base2 }
{ { void show ( )
//body1 // body2 {
} } cout << “In my mother’s name is: “ <<name;
cout << “In my mother’s age is: “ <<age;
}
class daughter : public father, public mother //derived class inheriting
{ //publicly
Class derived : visibility basel, visibility base2 char name [20] ; //the features of both the base class
{ int std;
//body3 public:
} void get ( ) ;
void show ( ) ;
Where the visibility refers to the access specifiers i.e. public, private or protected. Following };
program shows the multiple inheritance. void daughter :: get ( )
{
#include<iostream.h> father :: get ( ) ;
#include<conio . h> mother :: get ( ) ;
class father //Declaration of base classl cout << “child's name: “;
{ cin >> name;
int age ; cout << “child's standard”;
char flame [20] ; cin >> std;
public: }
void get ( ) ; void daughter :: show ( )
void show ( ) ; {
}; father :: show ( );
void father : : get ( ) nfather :: show ( ) ;
{ cout << “In child’s name is : “ <<name;
cout << “your father name please”; cout << “In child's standard: “ << std;
cin >> name; }
cout << “Enter the age”; main ( )
cin >> age; {
} clrscr ( ) ;
void father : : show ( ) daughter d1;
{ d1.get ( ) ;
cout<< “In my father’s name is: ‘ <<name<< “In my father’s age is:<<age; d1.show ( ) ;
} }
class mother //Declaration of base class 2
{
char name [20] ;
int age ;
46
Diagrammatic Representation of Multiple Inheritance is as follows: LECTURE-28
Father Mother
Hierarchical Inheritance
Private: Private:
int age; int age; Another interesting application of inheritance is to use is as a support to a hierarchical design of a
char name[20]; char name[20]; class program. Many programming problems can be cast into a hierarchy where certain features of
one level are shared by many others below that level for e.g.
Protected: Protected:
Accounts
Public: Public:
void get() void get() Saving Accounts Current Accounts
void show() void show()
Fixed deposit
In C++, such problems can be easily converted into hierarchies. The base class will include all the
features that are common to the subclasses. A sub-class can be constructed by inheriting the features
of base class and so on.
47
cout<< “father’s age please”; cin >> age; son S1;
} daughter D1 ;
void show ( ) S1. get ( ) ;
{ D1. get ( ) ;
cout << “In father’s name is ‘: “<<name; S1 .show( ) ;
cout << “In father’s age is: “<< age; D1. show ( ) ;
} }
};
class son : public father //derived class 1 Hybrid Inheritance
{ There could be situations where we need to apply two or more types of inheritance to design a
char name [20] ; program. Basically Hybrid Inheritance is the combination of one or more types of the inheritance.
int age ; Here is one implementation of hybrid inheritance.
public;
void get ( ) ;
void show ( ) ; //Program to show the simple hybrid inheritance
}; #include<i sos t ream. h>
void son : : get ( ) #include<conio . h>
class student //base class declaration
{
protected:
int r_no;
{ public:
father :: get ( ) ; void get _n (int a)
cout << “your (son) name please” << “in”; cin >>name; {
cout << “your age please” << “ln”; cin>>age; r_no =a;
} }
void son :: show ( ) void put_n (void)
{ {
father : : show ( ) ; cout << “Roll No. : “<< r_no;
cout << “In my name is : “ <<name; cout << “In”;
cout << “In my age is : “ <<age; }
} };
class daughter : public father //derived class 2. class test : public student
{ { //Intermediate base class
char name [15] ; protected : int parti, par 2;
int age;
public: public :
void get ( ) void get_m (int x, int y) {
{ parti = x; part 2 = y; }
father : : get ( ) ; void put_m (void) {
cout << “your (daughter’s) name please In” cin>>name; cout << “marks obtained: “ << “In”
cout << “your age please In”; cin >>age; << “Part 1 = “ << part1 << “in”
} << “Part 2 = “ << part2 << “In”;
void show ( ) }
{ };
father : : show ( ) ; class sports // base for result
cout << “in my father name is: “ << name << “ {
In and his age is : “<<age; protected : int score;
} public:
}; void get_s (int s) {
main ( ) score = s }
{ void put_s (void) {
clrscr ( ) ; cout << “ sports wt. : “ << score << “\n\n”;
48
} LECTURE-29
};
class result : public test, public sports //Derived from test Virtual Base Classes
& sports We have just discussed a situation which would require the use of both multiple and multi level
{ inheritance. Consider a situation, where all the three kinds of inheritance, namely multi-level,
int total; multiple and hierarchical are involved.
public:
void display (void); Let us say the 'child' has two direct base classes ‘parent1’ and ‘parent2’ which themselves has a
}; common base class ‘grandparent’. The child inherits the traits of ‘grandparent’ via two separate
paths. It can also be inherit directly as shown by the broken line. The grandparent is sometimes
referred to as ‘INDIRECT BASE CLASS’. Now, the inheritance by the child might cause some
void result : : display (void) problems. All the public and protected members of ‘grandparent’ are inherited into ‘child’ twice, first
{ via ‘parent1’ and again via ‘parent2’. So, there occurs a duplicacy which should be avoided.
total = part1 + part2 + score;
put_n ( ) ;. The duplication of the inherited members can be avoided by making common base class as the
put_m ( ); virtual base class: for e.g.
put_S ( ); class g_parent
cout << “Total score: “ <<total<< “\n” {
} //Body
main ( ) };
{ class parent1: virtual public g_parent
clrscr ( ) ; {
result S1; // Body
S1.get_n (347) ; };
S1.get_m (30, 35);
S1.get_s (7) ; class parent2: public virtual g_parent
S1.dciplay ( ) ; {
} // Body
};
Student Activity class child : public parent1, public parent2
1. What is the major use of multilevel Inheritance? {
2. How are arguments sent to the base constructors in multiple inheritance? Whose // body
responsibility is it. };
3. What is the difference between hierarchical and hybrid Inheritance.
When a class is virtual base class, C++ takes necessary care to see that only one copy
of that class is inherited, regardless of how many inheritance paths exists between
virtual base class and derived class. Note that keywords ‘virtual’ and ‘public’ can be
used in either order.
49
class test : virtual public student // Virtually declared common protected:
{ //base class 1 int x;
protected: public:
int part1; void get (int) ;
int part2; void show (void) ;
public: };
void get_m (int x, int y) void A : : get (int a)
{ part1= x; part2=y;} {x=a;}
void putm (void) void A : : show (void)
{ { cout << X ;}
cout << “marks obtained: “ << “\n”; Class A1 : Virtual Public A
cout << “part1 = “ << part1 << “\n”; {
cout << “part2 = “<< part2 << “\n”;
}
};
class sports : public virtual student // virtually declared common
{ //base class 2
protected: protected:
int score; int y ;
public: public:
void get_s (int a) { void get (int) ;
score = a ; void show (void);
} };
void put_s (void) void A1 :: get (int a)
{ cout << “sports wt.: “ <<score<< “\n”;} { y = a;}
}; void A1 :: show (void)
class result: public test, public sports //derived class {
{ cout <<y ;
private : int total ; {
public: class A2 : Virtual public A
void show (void) ; {
}; protected:
void result : : show (void) int z ;
{ total = part1 + part2 + score ; public:
put_n ( ); void get (int a)
put_m ( ); { z =a;}
put_s ( ) ; cout << “\n total score= “ <<total<< “\n” ; void show (void)
} { cout << z;}
main ( ) };
{ class A12 : public A1, public A2
clrscr ( ) ; {
result S1 ; int r, t ;
S1.get_n (345) public:
S1.get_m (30, 35) ; void get (int a)
S1.get-S (7) ; { r = a;}
S1. show ( ) ; void show (void)
} {t=x+y+z+r;
cout << “result =” << t ;
//Program to show hybrid inheritance using virtual base classes }
#include<iostream.h> };
#include<conio.h> main ( )
Class A {
{ clrscr ( ) ;
50
A12 r ; LECTURE-30
r.A : : get (3) ;
r.A1 : : get (4) ;
r.A2 : : get (5) ; Polymorphism:
r.get (6) ;
Introduction
r . show ( ) ;
} When an object is created from its class, the member variables and member functions are allocated
memory spaces. The memory spaces have unique addresses. Pointer is a mechanism to access these
memory locations using their address rather than the name assigned to them. You will study the
implications and applications of this mechanism in detail in this chapter.
Pointer is a variable which can hold the address of a memory location rather than the value at the
location. Consider the following statement
This statement instructs the compiler to reserve a 2-byte of memory location and puts the value 84 in
that location. Assume that the compiler allocates memory location 1001 to num. Diagrammatically,
the allocation can be shown as:
84 Value
Figure 9.1
As the memory addresses are themselves numbers, they can be assigned to some other variable For
example, ptr be the variable to hold the address of variable num.
Thus, we can access the value of num by the variable ptr. We can say “ptr points to num” as shown
in the figure below.
num num
84 1001
1001 2057
Fig 9.2
51
S1.bet (5) ;
Pointers to Objects S2.show ( );
}
An object of a class behaves identically as any other variable. Just as pointers can be defined in case o/p = 5
of base C++ variables so also pointers can be defined for an object type. To create a pointer variable
for the following class Pointers to Derived Classes
class employee {
Polymorphism is also accomplished using pointers in C++. It allows a pointer in a base class to point
int code; to either a base class object or to any derived class object. We can have the following Program
char name [20] ; segment show how we can assign a pointer to point to the object of the derived class.
public: class base
inline void getdata ( )= 0 ; {
//Data Members
inline void display ( )= 0 ; //Member Functions
}; };
class derived : public base
The following codes is written {
employee *abc; //Data Members
This declaration creates a pointer variable abc that can point to any object of employee type. //Member functions
};
this Pointer
void main ( ) {
C++ uses a unique keyword called "this" to represent an object that invokes a member function. 'this' base *ptr; //pointer to class base
is a pointer that points to the object for which this function was called. This unique pointer is called derived obj ;
and it passes to the member function automatically. The pointer this acts as an implicit argument to ptr = &obj ; //indirect reference obj to the pointer
all the member function, for e.g. //Other Program statements
class ABC
{ }
int a ; The pointer ptr points to an object of the derived class obj. But, a pointer to a derived class object
----- may not point to a base class object without explicit casting.
-----
}; For example, the following assignment statements are not valid
The private variable ‘a’ can be used directly inside a member function, like void main ( )
a=123; {
We can also use the following statement to do the same job. base obja;
this → a = 123 derived *ptr;
e.g. ptr = &obja; //invalid.... .explicit casting required
class stud //Other Program statements
{ }
int a; A derived class pointer cannot point to base class objects. But, it is possible by using explicit casting.
public: void main ( )
void set (int a) {
{ base obj ;
this → a = a; //here this point is used to assign a class level derived *ptr; // pointer of the derived class
} ‘a’ with the argument ‘a’ ptr = (derived *) & obj; //correct reference
void show ( ) //Other Program statements
{ }
cout << a;
} Student Activity
}; 1. Define Pointers.
main ( ) 2. What are the various operators of pointer? Describe their usage.
{ 3. How will you declare a pointer in C++?
stud S1, S2;
52
LECTURE-31 };
int point: : length ( )
{
Virtual Functions Function body
}
Virtual functions, one of advanced features of OOP is one that does not really exist but it« appears A virtual function cannot have a constructor member function but it can have the destructor member
real in some parts of a program. This section deals with the polymorphic features which are function.
incorporated using the virtual functions. class point {
int x ;
The general syntax of the virtual function declaration is: int y ;
class use_detined_name{ public:
private: virtual point (int xx, int yy) ; // constructors, error
public: void display ( ) ;
virtual return_type function_name1 (arguments); int length ( ) ;
virtual return_type function_name2(arguments); };
virtual return_type function_name3( arguments); A destructor member function does not take any argument and no return type can be specified for it
------------------ not even void.
}; class point {
To make a member function virtual, the keyword virtual is used in the methods while it is declared in int x ;
the class definition but not in the member function definition. The keyword virtual precedes the int y ;
return type of the function name. The compiler gets information from the keyword virtual that it is a public:
virtual function and not a conventional function declaration. virtual point (int xx, int yy) ; //invalid
void display ( ) ;
For. example, the following declararion of the virtual function is valid. int length ( ) ;
class point { It is an error to redefine a virtual method with a change of return data type in the derived class with
intx; the same parameter types as those of a virtuall method in the base class.
inty; class base {
public: int x,y ;
virtual int length ( ); public:
virtual void display ( ); virtual int sum (int xx, int yy ) ; //error
}; };
Remember that the keyword virtual should not be repeated in the definition if the definition occurs class derived: public base {
outside the class declaration. The use of a function specifier virtual in the function definition is intz ;
invalid. public:
virtual float sum (int xx, int yy) ;
For example };
class point { The above declarations of two virtual functions are invalid. Even though these functions take
intx ; identical arguments note that the return data types are different.
inty ; virtual int sum (int xx, int IT) ; //base class
public: virtual float sum (int xx, int IT) ; //derived class
virtual void display ( ); Both the above functions can be written with int data types in the base class as well as in the derived
}; class as
virtual void point: : display ( ) //error virtual int sum (int xx, int yy) ; //base class
{ virtual int sum (int xx, int yy) ; //derived class
Function Body Only a member function of a class can be declared as virtual. A non member function (nonmethod)
} of a class cannot be declared virtual.
A virtual function cannot be a static member since a virtual member is always a member of a virtual void display ( ) //error, nonmember function
particular object in a class rather than a member of the class as a whole. {
class point { Function body
int x ; }
int y ;
public:
virtual static int length ( ); //error
53
Student Activity #include <iostream.h>
1. What are virtual functions #include <conio.h>
2. What are pure virtual functions class baseA {
3. Define Virtual destructors. public :
virtual void display () {
cout<< “One \n”;
Late Binding }
As we studied in the earlier unit, late binding means selecting functions during the execution.
};
Though late binding requires some overhead it provides increased power and flexibility. The late
class derivedB : public baseA
binding is implemented through virtual functions as a result we have to declare an object of a class
{
either as a pointer to a class or a reference to a class.
public:
virtual void display(){
For example the following shows how a late binding or run time binding can be carried out with the
cout<< “Two\n”; }
help of a virtual function.
};
class base {
class derivedC: public derivedB
private :
{
int x;
public:
float y;
virtual void display ( ) {
public:
cout<< “Three \n”; }
virtual void display ( ) ;
};
int sum ( ) ;
void main ( ) {
};
//define three objects
class derivedD : public baseA
baseA obja;
{
derivedB objb;
private :
derivedC objc;
int x ;
base A *ptr [3]; //define an array of pointers to baseA
float y;
ptr [0] = &obja;
public:
ptr [1] = &objb;
void display ( ); //virtual
ptr [2] = &objc;
int sum ( ) ;
for ( int i = 0; i <=2; i ++ )
};
ptr [i]->display ( ); //same message for all objects
void main ( )
getche ( ) ;
{
}
baseA *ptr ;
Output
derivedD objd ;
One
ptr = &objd ;
Two
Other Program statements
Three
ptr- >di splay ( ) ; //run time binding
ptr->sum ( ) ; //compile time binding
The program listed below illustrates the static binding of the member functions of a class. In program
}
there are two classes student and academic. The class academic is derived from class student. The
two member function getdata and display are defined for both the classes. *obj is defined for class
Note that the keyword virtual is be followed by the return type of a member function if a run time is
student, the address of which is stored in the object of the class academic. The functions getdata ( )
to be bound. Otherwise, the compile time binding will be effected as usual. In the above program
and display ( ) of student class are invoked by the pointer to the class.
segment, only the display ( ) function has been declared as virtual in the base class, whereas the sum
( ) is nonvirtual. Even though the message is given from the pointer of the base class to the objects of
#include<iostream.h>
the derived class, it will not
#include<conio.h>
class student {
access the sum ( ) function of the derived class as it has been declared as nonvirtual. The sum ( )
private:
function compiles only the static binding.
int rollno;
char name [20];
The following program demonstrates the run time binding of the member functions of a class. The
public:
same message is given to access the derived class member functions from the array of pointers. As
void getdata ( );
function are declared as virtual, the C++ compiler invokes the dynamic binding.
void display ( );
54
}; private:
class academic: public student { introllno;
private: char name [20];
char stream; public:
public: virtual void getdata ( );
void getdata ( ); virtual void display ( );
void display ( ) ; };
}; class academic: public student {
void student:: getdata ( ) private :
{ char stream[10];
cout<< “enterrollno\n”; public:
cin>>rollno; void getdata { };
cout<< “enter name \n”; void display ( ) ;
cin>>name; };
} void student: : getdata ( )
void student:: display ( ) {
{ cout<< “enter rollno\n”;
cout<< “the student’s roll number is “<<rollno<< “and name is”<<name ; cin >> rollno;
cout<< endl; cout<< “enter name \n”;
} cin >>name;
void academic :: getdata ( ) }
{ void student:: display ( )
cout<< “enter stream of a student? \n”; {
cin >>stream; cout<< “the student’s roll number is”<<rollno<< “and name is”<<name;
} cout<< end1;
void academic :: display ( ) { }
cout<< “students stream \n”; void academic: : getdata ( )
cout <<stream<< endl; {
} cout << “enter stream of a student? \n”;
void main ( ) cin>> stream;
{ }
student *ptr ; void academic:: display ( )
academic obj ; {
ptr=&obj; cout<< “students stream \n”;
ptr->getdata ( ) ; cout<< stream << endl;
ptr->display ( ) ; }
getche ( ); void main ( )
} {
output student *ptr ;
enter rollno academic obj ;
25 ptr = &obj ;
enter name ptr->getdata ( );
raghu ptr->dlsplay ( );
the student’s roll number is 25 and name is raghu getch ( );
}
The program listed below illustrates the dynamic binding of member functions of a class. In this output
program there are two classes student and academic. The class academic is derived from student. enter stream of a student?
Student function has two virtual functions getdata ( ) and display (). The pointer for student class is Btech
defined and object . for academic class is created. The pointer is assigned the address of the object students stream
and function of derived class are invoked by pointer to student. Btech
#include <iostream.h>
#include <conio.h>
class student {
55
LECTURE-32 }
void main ( )
{
Pure Virtual Functions employee *ptr ;
grade obj ;
Generally a function is declared virtual inside a base class and we redefine it the derived classes. The ptr = &obj ;
function declared in the base class seldom performs any task. ptr->getdata ( ) ;
ptr->display ( ) ;
The following program demonstrates how a pure virtual function is defined, declared and invoked getche ( ) ;
from the object of a derived class through the pointer of the base class. In the example there are two }
classes employee and grade. The class employee is base class and the grade is derived class. The Output
functions getdata ( ) and display ( ) are declared for both the classes. For the class employee the enter employee’s grade A
functions are defined with empty body or no code inside the function. The code is written for the enter the salary 250000
grade class. The methods of the derived class are invoked by the pointer to the base class. Grade salary
A 250000
#include<iostream.h>
#include<conio.h> Object Slicing:
class employee { In C++, a derived class object can be assigned to a base class object, but the other way is not
int code possible.
char name [20] ; class Base { int x, y; };
public:
class Derived : public Base { int z, w; };
virtual void getdata ( ) ;
int main()
virtual void display ( ) ; {
Derived d;
}; Base b = d; // Object Slicing, z and w of d are sliced off
class grade: public employee }
{
char grd [90] ; Object Slicing happens when a derived class object is assigned to a base class object, additional
float salary ; attributes of a derived class object are sliced off to form the base class object.
public :
void getdata ( ) ; #include <iostream>
void display ( ); using namespace std;
};
class Base
void employee :: getdata ( )
{
{ protected:
} int i;
void employee:: display ( ) public:
{ Base(int a) { i = a; }
virtual void display()
} { cout << "I am Base class object, i = " << i << endl; }
void grade : : getdata ( ) };
{
cout<< “ enter employee’s grade “; class Derived : public Base
cin> > grd ; {
cout<< “\n enter the salary “ ; int j;
public:
cin>> salary; Derived(int a, int b) : Base(a) { j = b; }
} virtual void display()
void grade : : display ( ) { cout << "I am Derived class object, i = "
{ << i << ", j = " << j << endl; }
};
cout«" Grade salary \n";
cout« grd« " "« salary« endl;
56
// Global method, Base class object is passed by value
void somefunc (Base obj) LECTURE-33
{
obj.display();
} C++ Function Overriding
int main()
{
If base class and derived class have member functions with same name and arguments. If you create
Base b(33); an object of derived class and write code to access that member function then, the member function
Derived d(45, 54); in derived class is only invoked, i.e., the member function of derived class overrides the member
somefunc(b); function of base class. This feature in C++ programming is known as function overriding.
somefunc(d); // Object Slicing, the member j of d is sliced off
return 0;
}
Output:
We can avoid above unexpected behavior with the use of pointers or references. Object slicing
doesn’t occur when pointers or references to objects are passed as function arguments since a pointer
or reference of any type takes same amount of memory. For example, if we change the global
method myfunc() in the above program to following, object slicing doesn’t happen.
Output:
We get the same output if we use pointers and change the program to following.
Object slicing can be prevented by making the base class function pure virtual there by disallowing
object creation. It is not possible to create the object of a class which contains a pure virtual method.
57
{
public:
virtual void show() = 0; //Pure Virtual Function
};
int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
In the above example Base class is abstract, with pure virtual show() function, hence we cannot
create object of base class.
Abstract Class
Why can't we create Object of Abstract Class ?
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are
used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide When we create a pure virtual function in Abstract class, we reserve a slot for a function in the
definition to the pure virtual function, otherwise they will also become abstract class. VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be
incomplete.
Characteristics of Abstract Class
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of
1. Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be object for such class and will display an errror message whenever you try to do so.
created.
2. Abstract class can have normal functions and variables along with a pure virtual function.
3. Abstract classes are mainly used for Upcasting, so that its derived classes can use its
interface.
4. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they
will become Abstract too.
Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and
ends with = 0. Here is the syntax for a pure virtual function,
58
LECTURE-34 throw construct:
The keyword throw is used to raise an exception when an error is generated in the comutation. the
throw expression initialize a temporary object of the typeT used in thorw (T arg).
Exception Handling: syntax:
throw T;
Exception refers to unexpected condition in a program. The unusual conditions could be faults,
causing an error which in turn causes the program to fail. The error handling mechanism of c++ is catch construct:
generally referred to as exception handling.
The exception handler is indicated by the catch keyword. It must be used immediately after the
Generally , exceptions are classified into synchronous and asynchronous exceptions.. The exceptions statements marked by the try keyword. The catch handler can also occur immediately after another
which occur during the program execution, due to some fault in the input data or technique that is not catch Each handler will only evaluate an exception that matches.
suitable to handle the current class of data. with in a program is known as synchronous exception. syn:
Example: catch(T)
errors such as out of range,overflow,underflow and so on. {
// error meassges
The exceptions caused by events or faults unrelated to the program and beyond the control of }
program are asynchronous exceptions.
For example, errors such as keyboard interrupts, hardware malfunctions, disk failure and so on. try construct:
The try keyboard defines a boundary within which an exception can occur. A block of code in which
exception handling model: an exception can occur must be prefixed by the keyword try. Following the try keyword is a block of
code enclosed by braces. This indicates that the prepared to test for the existence of exceptions. If an
When a program encounters an abnormal situation for which it in not designed, the user may transfer exception occurs, the program flow is interrupted.
control to some other part of the program that is designed to deal with the problem. This is done by
throwing an exception. The exception handling mechanism uses three blocks: try, throw and catch. try
The try block must be followed immediately by a handler, which is a catch block. If an exception is {
thrown in the try block the program control is transferred to the appropriate exception handler. The …
program should attempt to catch any exception that is thrown by any function. The relationship of if (failure)
these three exceptions handling constructs called the exception handling model is shown in figure: throw T;
}
catch(T)
{
…
}
try block
perform operation which may throw
example:
or invoke external function if needed #include<iostream.h>
void main()
{
invoke function having throw block int a,b;
throw block cout<<”enter two numbers:”;
if (failure) cin>>a>>b;
throw object try
{
exception if (b= =0)
throw b;
catch block
else
catches all exceptions thrown from
cout<a/b;
within try block
}
catch(int x)
{
cout<<”2nd operand can’t be 0”;
}
}
59
LECTURE-35 }
catch (char c)
{
Array reference out of bound: cout<<”caught a character…”;
#define max 5 }}
class array void main()
{ {
private: test(1);
int a[max]; test(-1);
public: test(0);
int &operator[](int i) }
{
if (i<0 || i>=max) catch all
throw i; void test(int x)
{
else try{
return a[i]; if (x==1)
} throw x;
}; else if (x==-1)
void main() throw 3.4;
{ else if (x==0)
array x; throw ‘s’;
try }
{ catch (…)
cout<<”trying to refer a[1]…” {
x[1]=3; cout<<”caught an error…”;
cout<<”trying to refer a[13]…” }
x[13]=5;
}
catch(int i)
{
cout<<”out of range in array references…”;
}
}
60
Module-03: //Sample Program to demonstrate Containership
LECTURE-36 #include < iostream.h >
#include < conio.h >
#include < iomanip.h >
Containership in C++ #include< stdio.h >
const int len=80;
When a class contains objects of another class or its members, this kind of relationship is class employee
called containership or nesting and the class which contains objects of another class as its members is {
called as container class. private:
char name[len];
Syntax for the declaration of another class is: int number;
public:
void get_data()
{
Class class_name1 cout << "\n Enter employee name: ";
cin >> name;
{ cout << "\n Enter employee number: ";
cin >> number;
——– }
void put_data()
——– {
cout << " \n\n Employee name: " << name;
}; cout << " \n\n Employee number: " << number;
}
Class class_name2 };
class manager
{ {
private:
——– char dept[len];
int numemp;
——— employee emp;
public:
}; void get_data()
{
Class class_name3 emp.get_data();
cout << " \n Enter department: ";
{ cin >> dept;
cout << "\n Enter number of employees: ";
Class_name1 obj1; // object of class_name1 cin >> numemp;
}
Class_name2 obj2; // object of class_name2 void put_data()
{
———- emp.put_data();
cout << " \n\n Department: " << dept;
———– cout << " \n\n Number of employees: " << numemp;
}
}; };
class scientist
{
private:
int pubs,year;
employee emp;
public:
61
void get_data() Difference between Inheritance and Containership :
{
emp.get_data(); Containership: Containership is the phenomenon of using one or more classes within the definition
cout << " \n Number of publications: ";
of other class. When a class contains the definition of some other classes, it is referred to as
cin >> pubs;
cout << " \n Year of publication: "; composition, containment or aggregation. The data member of a new class is an object of some
cin >> year;
other class. Thus the other class is said to be composed of other classes and hence referred to as
}
void put_data() containership. Composition is often referred to as a “has-a” relationship because the objects of the
{
composite class have objects of the composed class as members.
emp.put_data();
cout << "\n\n Number of publications: " << pubs;
cout << "\n\n Year of publication: "<< year;
}
}; Inheritance: Inheritance is the phenomenon of deriving a new class from an old one. Inheritance
void main()
supports code reusability. Additional features can be added to a class by deriving a class from it and
{
manager m1; then by adding new features to it. Class once written or tested need not be rewritten or redefined.
scientist s1;
Inheritance is also referred to as specialization or derivation, as one class is inherited or derived from
int ch;
clrscr(); the other. It is also termed as “is-a” relationship because every object of the class being defined is
do
also an object of the inherited class.
{
cout << "\n 1.manager\n 2.scientist\n";
cout << "\n Enter your choice: ";
cin >> ch;
switch(ch)
{
case 1:
cout << "\n Manager data:\n";
m1.get_data();
cout << "\n Manager data:\n";
m1.put_data();
break;
case 2:cout << " \n Scientist data:\n";
s1.get_data();
cout << " \n Scientist data:\n";
s1.put_data();
break;
}
cout << "\n\n To continue Press 1 -> ";
cin >> ch;
}
while(ch==1);
getch();
}
62
LECTURE-37 {
if (a>b)
return a;
Template: else
Template supports generic programming, which allows developing reusable software components return b;
such as functions, classes, etc supporting different data types in a single frame work. }
A template in c++ allows the construction of a family of template functions and classes to perform void main()
the same operation o different data types. The templates declared for functions are called class {
templates. They perform appropriate operations depending on the data type of the parameters passed char ch1,ch2;
to them. cout<<”enter two characters:”;
cin>>ch1>>ch2;
Function Templates: cout<<max(ch1,ch2);
A function template specifies how an individual function can be constructed. int a,b;
template <class T> cout<<”enter a,b:”;
return type functionnm(T arg1,T arg2) cin>>a>>b;
{ cout<<max(a,b);
fn body; float p,q;
} cout<<”enter p,q:”;
cin>>p>>q;
For example: cout<<max(p,q);
Input two number and swap their values }
63
{ LECTURE-38
cout<<sum(4,5.5);
cout<sum(5.4,3);
} Class Template
similar to functions, classes can also be declared to operate on different data types. Such classes are
class templates. a class template specifies how individual classes can be constructed similar to
normal class definition. These classes model a generic class which support similar operations for
different data types.
syn:
template <class T>
class classnm
{
T member1;
T member2;
…
…
public:
T fun();
…
..
};
example:
Input n numbers into an array and print the element is ascending order.(array sorting)
64
for (i=0;i<n;i++) LECTURE-39
{
cout<<a[i]<<endl; Virtual destructors:
}
} Just like declaring member functions as virtual, destructors can be declared as virtual, whereas
void sort( ) constructors can not be virtual. Virtual Destructors are controlled in the same way as virtual
{ functions. When a derived object pointed to by the base class pointer is deleted, destructor of the
T k; derived class as well as destructor of all its base classes are invoked. If destructor is made as non
int i,j; virtual destructor in the base class, only the base class’s destructor is invoked when the object is
for(i=0;i<n-1;i++) deleted.
{ #icnlude<iostream.h>
for (j=0;j<n;j++) #include<string.h>
{ class father
if (a[i]>a[j]) {
{ protected:
k=a[i]; char *fname;
a[i]=a[j]; public:
a[j]=k; father(char *name)
} {
} fname=new char(strlen(name)+1);
} strcpy(fname,name);
} }
}; virtual ~father()
void main() {
{ delete fname;
array <int>x; cout<<”~father is invoked…”;
x.getdata(); }
x.sort();
x.putdata(); virtual void show()
{
array <float> y; cout<<”father name…”<<fname;
y.getdata(): }
y.sort(); };
y.putdata();
} class son: public father
{
protected:
char *s_name;
public:
son(char *fname,char *sname):father(fname)
{
sname=new char[strlen(sname)+1];
strcpy(s_name,sname);
}
~son()
{
delete s_name;
cout<<”~son() is invoked”<<endl;
}
void show()
{
cout<<”father’s name”<<fname;
cout<<”son’s name:”<<s_name;
65
} for(int i=0;i<size;i++)
}; c.v[i]=a*b.v[i];
void main() return c;
{ }
father *basep; istream &operator>>(istream &din,vector &b)
basep =new father (“mona”); {
cout<<”basep points to base object…” for(int i=0;i<size;i++)
basep->show(); din>>b.v[i];
delete basep; }
basep=new son(“sona”,”mona”); ostream &operator<<(ostream &dout,vector &b)
cout<<”base points to derived object…”; {
basep->show(); for(i=0;i<size;i++)
delete basep; dout<<a[i];
} return dout;
}
int x[size]={2,4,6};
int main()
{
vector m;
Overloading of >> and << operator vector n=x;
cout<<”enter elements of vector m”;
#define size 5 cin>>m;
class vector cout<<m;
{ vector p,q;
int v[size]; p=2*m;
public: q=n*2;
vector(); cout<<p;
friend vector operator*(int a,vector b); cout<<q;
friend vector operator *(vector b,int a);
friend istream &operator>>(istream &,vector &); }
friend ostream &operator<<(ostream &,vector &);
};
vector :: vector()
{
for(int i=0;i<size;i++)
v[i]=0;
}
vector::vector(int *x)
{
for (int i=0;i<size;i++)
v[i]=x[i];
}
vector operator*(int a,vector b)
{
vector c;
for(int i=0;i<size;i++)
c.v[i]=a*b.v[i];
return c;
}
66
LECTURE-40
data1 data2......dataN The function put(), a member of ostream class, can be used to output a line of text, character
by character. For example,
The input data are separated by white spaces and should match the type of variable in the cin cout << put (‘x’);
list. Spaces, newlines and tabs will be skipped. displays the character x and
cout << put (ch) ;
The operator >> reads the data character by character and assigns it to the indicated location. displays the value of variable ch.
The reading for a variable will be terminated at the encounter of a white space or a character that The variable ch must contain a character value. We can also use a number as an argument to
does not match the destination type. the function put (). For example,
For example, consider the following code: cout << put (68) ;
displays the character D. This statement will convert the int value 90 to a char value and display the
int code; character whose ASCII value is 68,
cin >> code; The following segment of a program reads a line of text from the keyboard and displays it on
the screen.
Suppose the following data is given as input: char c; .
cin.get (c) //read a character
1267E
while (c!= ‘\n’)
The operator will read the characters up to 7 and the value 1267 is assigned to code. The {
character E remains in the input stream and will be input to the next cin statement. The general cout<< put(c); //display the character on screen cin.get (c ) ;
format of outputting data: }
cout << iteml <<item2 << .. ..<< itemN;
The items, item1 through itemN may be variables or constants of any basic types.
67
The getline () and write () Functions
Manipulators are special functions that can be included in these statements to alter the format
We can read and display a line of text more efficiently using the line-oriented input/output parameters of a stream. The table given below shows some important! manipulator functions that are
functions getline() and write(). The getline() function reads a whole line of text that ends with a frequently used. To access these manipulators, the file iomanip.h should be included in the program.
newline character. This function can be invoked by using the object cin as follows:
cin.getline(line, size); Table 10.2
This function call invokes the function which reads character input into the variable line. The Manipulator Equivalent Ios function
reading is terminated as soon as either the newline character '\n' is encountered or size number of setw() width()
characters are read (whichever occurs first). The newline. character is read but not saved. Instead, it Setprecision() Precision()
is replaced by the null character. Setfill() fill()
For example; consider the following code: setiosflags() self()
char name [20] ; Resetiosflags() Unself()
cin.getline(name, 20);
Assume that we have given the following input through the keyboard: In addition to these functions supported by the C++ library, we can create our own
Neeraj good manipulator functions to provide any special output formats.
This input will be read correctly and assigned to the character array name. Let us suppose the
input is as follows:
Object Oriented Programming Student Activity
In this case, the input will be terminated after reading the following 19 characters: 1. What is a stream?
Object Oriented Pro
2. Define put ( ) and get ( ) functions
After reading the string/ cin automatically adds the terminating null character to the character 3. What is the difference between getline ( ) and get ( ) functions?
array.
Remember, the two blank spaces contained in the string are also taken into account, i.e. 4. Define write ( ) functions.
between Objects and Oriented and Pro. 5. What are manipulators?
We can also read strings using the operator >> as follows:
cin >> name;
But remember cin can read strings that do not contain white space. This means that cin can Streams
read just one word and not a series of words such as “Neeraj good”.
C++ is designed to work with a wide variety of devices including terminals, disks, and tape
Formatted Console I/O Operations drives. Although each device is very different, the system supplies an interface to the programmer
that is independent of the actual device being accessed, This interface is known as stream.
C++ supports a number of features that could be used for formatting the output. These A stream is a sequence of bytes. It acts either as a source from which the input data can be
features include: obtained or as a destination to which the output data can be sent. The source stream that provides
ios class functions and flags. data to the program is called the output stream. In other words, a program extracts the bytes from an
Manipulators. input stream and inserts bytes into an output stream.
The data in the input stream can come from the keyboard or any other storage device.
User-defined output functions.
Similarly, the data in the output stream can go to the screen or any other storage device. As
The ios class contains a large number of member functions that could be used to format the
mentioned earlier, a stream acts as an interface between the program and the input/output device.
output in a number of ways. The most important ones among them are listed below.
Therefore, a C++ program handles data (input or output) independent of the devices used.
C++ contains several pre-defined streams that are automatically opened when a
Table 10.1
program begins its execution. They include cin and cout which have been used very often in our
Function Task earlier programs. We know that cin represents the input stream connected to the standard input
width() To specify the required field size for displaying an output value device (usually the keyboard) and cout represents the output stream connected to the standard output
device (usually the screen). Note that the keyboard and the screen are default options. We can
Precision() To specify the number of digits to be displayed after the decimal point redirect streams to other devices or files, if necessary.
of a float value
fill() To specify a character that is used to fill the unused portion of a field. I/O Operations
self() To specify format flags that can control the form of output display
(such as Left-justification and right-justification). Input and Output statements of computer languages are used to provide commu-nications
between the user and the program. In most of the computer languages, input and output are done
Unself() To clear the flags specified.
68
through statements. But in C++, these operations are carried out through its built-in functions. The
I/O functions are designed in header files like fstream.h, iostream.h etc.
LECTURE-41
Through these functions, data can be read from or written to files or standard input/output
devices like keyboard and VDU. This execution of a program can be interrupted by input/output
calls. Hence the data can be entered or output can be retrieved during execution.
The file, stream classes support a number of member functions for performing the input and Namespaces :
output operations on files. One pair of functions, pot( ) and get( ), are designed for handling a single
character at a time. Another pair of functions, Scopes
write() and readQ, are designed to write and read blocks of binary data. Named entities, such as variables, functions, and compound types need to be declared before being
used in C++. The point in the program where this declaration happens influences its visibility:
put( ) and get( )Functions
The function put( ) writes a single character to the associated stream. Similarly, the function An entity declared outside any block has global scope, meaning that its name is valid anywhere in
get ( ) reads a single character from the, associated stream. The program, requests for a string. On the code. While an entity declared within a block, such as a function or a selective statement, has
receiving the string, the program writes it, character, by character, to the file using the pot() function block scope, and is only visible within the specific block in which it is declared, but not outside it.
in a for loop. Note that the length of the string is used to terminate the for loop.
Variables with block scope are known as local variables.
C++ provides a number of useful predefined stream classes for console input/output
operations. Some of the C++ the predefined stream objects are listed below. For example, a variable declared in the body of a function is a local variable that extends until the
cin This is the name of standard input stream, usually keyboard. The end of the the function (i.e., until the brace } that closes the function definition), but not outside it:
corresponding name in C is stdin.
cout This is the name of standard output stream, usually screen of the monitor. The int foo; // global variable
corresponding name in C is stdout.
cerr This is the name of standard error output stream, usually screen of the monitor. The int some_function ()
{
corresponding name in C is stderr. int bar; // local variable
clog This is another version of cerr. It provides buffer to collect errors. C does not have a bar = 0;
stream equivalent to this. }
In their default roles, these streams are tied up with the keyboard and screen of the monitor as
describe above. However, you can redirect them from and to other devices and files. int other_function ()
{
foo = 1; // ok: foo is a global variable
bar = 2; // wrong: bar is not visible from this function
}
Keywords
put (): A member of ostream class, could be used to output a line of text, character by
character. In each scope, a name can only represent one entity. For example, there cannot be two variables with
Get (): A member of istream class, used to input a single character at a line. the same name in the same scope:
Getline (): The get line ( ) function reads a whole line of -text that ends with a new line
character. This function could be invoked by using the object cin. int some_function ()
Manipulators: Special functions that can be included in console I/O statements to alter the {
format-parameters of a stream int x;
x = 0;
double x; // wrong: name already used in this scope
Streams: C++ is designed to work with a wide variety of devices including, disks and take drives. x = 0.0;
Although each device is very different the system suppliers an interface to the }
programmer that is independent of the actual device accessed. This interface is known as
stream.
The visibility of an entity with block scope extends until the end of the block, including inner blocks.
Output stream: The source stream that provides data to the program is called the.output stream. Nevertheless, an inner block, because it is a different block, can re-utilize a name existing in an outer
scope to refer to a different entity; in this case, the name will refer to a different entity only within
the inner block, hiding the entity it names outside. While outside it, it will still refer to the original
entity. For example:
138 P.T.O
69
using namespace std;
1 myNamespace::a
output: 2 myNamespace::b
inner block:
x: 50
y: 50
outer block: Namespaces are particularly useful to avoid name collisions. For example:
x: 10
y: 50 // namespaces
Note that y is not hidden in the inner block, and thus accessing y still accesses the outer variable. #include <iostream>
using namespace std;
Variables declared in declarations that introduce a block, such as function parameters and variables
namespace foo
declared in loops and conditions (such as those declared on a for or an if) are local to the block they {
introduce. int value() { return 5; }
}
namespace bar
{
Namespaces const double pi = 3.1416;
double value() { return 2*pi; }
Only one entity can exist with a particular name in a particular scope. This is seldom a problem for }
local names, since blocks tend to be relatively short, and names have particular purposes within
int main () {
them, such as naming a counter variable, an argument, etc... cout << foo::value() << '\n';
cout << bar::value() << '\n';
But non-local names bring more possibilities for name collision, especially considering that libraries cout << bar::pi << '\n';
may declare many functions, types, and variables, neither of them local in nature, and some of them return 0;
}
very generic.
Namespaces allow us to group named entities that otherwise would have global scope into narrower output:
scopes, giving them namespace scope. This allows organizing the elements of programs into
5
different logical scopes referred to by names. 6.2832
3.1416
The syntax to declare a namespaces is:
In this case, there are two functions with the same name: value. One is defined within the
namespace identifier namespace foo, and the other one in bar. No redefinition errors happen thanks to namespaces.
{ Notice also how pi is accessed in an unqualified manner from within namespace bar (just as pi),
named_entities while it is again accessed in main, but here it needs to be qualified as bar::pi.
}
Namespaces can be split: Two segments of a code can be declared in the same namespace:
Where identifier is any valid identifier and named_entities is the set of variables, types and
functions that are included within the namespace. For example: 1 namespace foo { int a; }
139 P.T.O 140 P.T.O
70
2 namespace bar { int b; } }
3 namespace foo { int c; }
namespace second
{
double x = 3.1416;
This declares three variables: a and c are in namespace foo, while b is in namespace bar. double y = 2.7183;
Namespaces can even extend across different translation units (i.e., across different files of source }
code).
int main () {
using namespace first;
cout << x << '\n';
cout << y << '\n';
using cout << second::x << '\n';
cout << second::y << '\n';
return 0;
The keyword using introduces a name into the current declarative region (such as a block), thus }
avoiding the need to qualify the name. For example:
output:
// using
#include <iostream> 5
using namespace std; 10
3.1416
namespace first 2.7183
{
int x = 5; In this case, by declaring that we were using namespace first, all direct uses of x and y without
int y = 10; name qualifiers were also looked up in namespace first.
}
using and using namespace have validity only in the same block in which they are stated or in the
namespace second
{ entire source code file if they are used directly in the global scope. For example, it would be possible
double x = 3.1416; to first use the objects of one namespace and then those of another one by splitting the code in
double y = 2.7183; different blocks:
}
// using namespace example
int main () { #include <iostream>
using first::x; using namespace std;
using second::y;
cout << x << '\n'; namespace first
cout << y << '\n'; {
cout << first::y << '\n'; int x = 5;
cout << second::x << '\n'; }
return 0;
} namespace second
Output: {
5 double x = 3.1416;
2.7183 }
10
3.1416 int main () {
{
using namespace first;
Notice how in main, the variable x (without any name qualifier) refers to first::x, whereas y refers cout << x << '\n';
to second::y, just as specified by the using declarations. The variables first::y and second::x }
can still be accessed, but require fully qualified names. {
using namespace second;
cout << x << '\n';
The keyword using can also be used as a directive to introduce an entire namespace: }
// using return 0;
#include <iostream> }
using namespace std;
71
Namespace aliasing using namespace std;
int x;
Existing namespaces can be aliased with new names, with the following syntax:
int main ()
namespace new_name = current_name; {
int y;
cout << x << '\n';
cout << y << '\n';
The std namespace return 0;
}
All the entities (variables, types, constants, and functions) of the standard C++ library are declared Output:
within the std namespace. Most examples in these tutorials, in fact, include the following line: 0
4285838
using namespace std;
The actual output may vary, but only the value of x is guaranteed to be zero. y can actually contain
just about any value (including zero).
This introduces direct visibility of all the names of the std namespace into the code. This is done in
these tutorials to facilitate comprehension and shorten the length of the examples, but many
programmers prefer to qualify each of the elements of the standard library used in their programs.
For example, instead of:
Whether the elements in the std namespace are introduced with using declarations or are fully
qualified on every use does not change the behavior or efficiency of the resulting program in any
way. It is mostly a matter of style preference, although for projects mixing libraries, explicit
qualification tends to be preferred.
Storage classes
The storage for variables with global or namespace scope is allocated for the entire duration of the
program. This is known as static storage, and it contrasts with the storage for local variables (those
declared within a block). These use what is known as automatic storage. The storage for local
variables is only available during the block in which they are declared; after that, that same storage
may be used for a local variable of some other function, or used otherwise.
But there is another substantial difference between variables with static storage and variables with
automatic storage:
- Variables with static storage (such as global variables) that are not explicitly initialized are
automatically initialized to zeroes.
- Variables with automatic storage (such as local variables) that are not explicitly initialized are left
uninitialized, and thus have an undetermined value.
For example:
// static vs automatic storage
#include <iostream>
72
Lecture-42:
New & Delete Operators+ new operator
void main()
Dynamic memory allocation means creating memory at runtime. For example, when we declare an {
array, we must provide size of array in our source code to allocate memory at compile time.
But if we need to allocate memory at runtime me must use new operator followed by data type. If int size,i;
we need to allocate memory for more than one element, we must provide total number of elements
required in square bracket[ ]. It will return the address of first byte of memory. int *ptr;
delete ptr;
}
//deallocte memory for one element
Output :
Enter size of Array : 5
delete[] ptr;
Enter any number : 78
//deallocte memory for array
Enter any number : 45
Enter any number : 12
Enter any number : 89
Enter any number : 56
Example of c++ new and delete operator
73