0% found this document useful (0 votes)
164 views

C Notes

The document discusses key concepts in object-oriented programming including objects, classes, paradigms, and the differences between procedural and object-oriented programming. It defines objects as instances of classes that have attributes and behaviors. Classes provide blueprints for objects and define what they will consist of and what operations can be performed on them. The document contrasts procedural programming, which emphasizes functions and passing data between them, with object-oriented programming, which emphasizes data encapsulation and passing messages between objects.

Uploaded by

Avi Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
164 views

C Notes

The document discusses key concepts in object-oriented programming including objects, classes, paradigms, and the differences between procedural and object-oriented programming. It defines objects as instances of classes that have attributes and behaviors. Classes provide blueprints for objects and define what they will consist of and what operations can be performed on them. The document contrasts procedural programming, which emphasizes functions and passing data between them, with object-oriented programming, which emphasizes data encapsulation and passing messages between objects.

Uploaded by

Avi Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

1

UNIT-1
Object Oriented Programming
Programming language
A programming language is a formal computer language or constructed language
designed to communicate instructions to a machine, particularly a computer.
Programming languages can be used to create programs to control the behavior
of a machine or to express algorithms.
Features of a Programming Language

 Readability: A good high-level language will allow programs to be written in


some ways that resemble a quite-English description of the underlying algorithms.
If care is taken, the coding may be done in a way that is essentially self-
documenting.
 Portability: High-level languages, being essentially machine independent,
should be able to develop portable software.
 Generality: Most high-level languages allow the writing of a wide variety of
programs, thus relieving the programmer of the need to become expert in many
diverse languages.
 Brevity: Language should have the ability to implement the algorithm with
less amount of code. Programs expressed in high-level languages are often
considerably shorter than their low-level equivalents.
 Error checking: Being human, a programmer is likely to make many
mistakes in the development of a computer program. Many high-level languages
enforce a great deal of error checking both at compile-time and at run-time.
 Cost: The ultimate cost of a programming language is a function of many of
its characteristics.
 Familiar notation: A language should have familiar notation, so it can be
understood by most of the programmers.
 Quick translation: It should admit quick translation.
 Efficiency: It should permit the generation of efficient object code.
 Modularity: It is desirable that programs can be developed in the language
as a collection of separately compiled modules, with appropriate mechanisms for
ensuring self-consistency between these modules.
 Widely available: Language should be widely available and it should be
possible to provide translators for all the major machines and for all the major
operating systems.
Types of programming language: procedural, non-procedural
Procedural languages are used in the traditional programming that is based on
algorithms or a logical step-by-step process for solving a problem. A procedural
programming language provides a programmer a means to define precisely each
step in the performance of a task Non-procedural programming languages allow
2

users and professional programmers to specify the results they want without
specifying how to solve the problem.
Examples:FORTRAN,C++,COBOL,ALGOL etc

Non-procedural language is concerned with the WHAT not the HOW. Non-proc
languages are those languages where you specify what conditions the answer
should satisfy, but not how to obtain it.
Examples: SQL, Visual Basic, etc
Non-procedural:
1)Non-Procedural language directs the computer what to do not and how to do
2)It is easy to learn
3)It requires a few non-procedural instructions.
4) It can be used professional and non-technical users

Object oriented and object based language


Object-oriented language supports all the features of OOPs . Theses language
doesn't have in-built object. For example C++, C#, Java etc.
Object-based language doesn't support all the features of OOPs like
Polymorphism and Inheritance Object-based language has in-built object like
javascript has window object. Object-based languages are Javascript, VB etc.
Difference Between Object Based and Object Oriented Languages
Object Based Language Object Oriented Language
Support of Object Based Language Object Oriented Language supports
features does not support all the all the features of Oops.
features of Oops
Inheritance Object Based Language Object Oriented Language supports
Does Not Support Oops all the Features of Oops including
feature i.e. Inheritance. Inheritance.
Polymorphism Object Based Language Object Oriented Language supports
Does Not Support Oops all the Features of Oops including
feature i.e. polymorphism. polymorphism.
Sample Visual Basic is an Object Java is an Object Oriented Languages
based Programming because it supports all the concepts
Language because you can of Oops like Data Encapsulation,
use class and Object here Polymorphism,Inheritance,Data
3

but can not inherit one Abstraction , Dynamic Binding etc.


class from another class
i.e. it does not support
Inheritance.
Example Javascript, VB C#, Java, VB. Net are example of
are example of Object Object Oriented Languages.
Based Language.

Programming Paradigm
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming
language or also we can say it is a method to solve a problem using tools and
techniques that are available to us following some approach. There are lots for
programming language that are known but all of them need to follow some
strategy when they are implemented and this methodology/strategy is
paradigms. Apart from varieties of programming language there are lots of
paradigms to fulfill each and every demand. They are discussed below:

Difference between procedural and object oriented language

Subject of Procedure Oriented Object Oriented Programming


Difference Programming (POP) (OOP)
Problem Decompose the main problem Decompose the main problem
decomposition in small parts called functions. in small parts called objects.
Connects small parts of the Connects small parts of the
Connections of
program by passing parameters program by passing messages.
parts
& using operating system.
4

Emphasizing Emphasizes on functions. Emphasizes on data.


In large programs, most Each object controls data under
Use of data
functions use global data. it.
Data may get passed from one Data never get passed from one
function to another. object to another.
Passing of data

Appropriate & effective Data stay secured as no external


Security of data techniques are unavailable to function can use data of an
secure the data. object.
Modification of a completed Modifications are easy as
Modification of
program is very difficult and it objects stay independent to
program
may affect the whole program. declare and define.
Designing Employs top-down approach Employs bottom-up approach
approach for designing programs. for designing.
In large programs, it is very As data and functions stay
Data
difficult to find what data has close, it is easy to identify data.
identification
been used by which function.
Languages like C, FORTRAN, Example of OOP are : C++, JAVA,
Used languages
COBOL etc. use POP. VB.NET, C#.NET
Access POP does not have any accessOOP has access specifiers
Specifiers specifier. named Public, Private,
Protected, etc.
Overloading In POP, Overloading is not In OOP, overloading is possible
possible. in the form of Function
Overloading and Operator
Overloading.
5

Object Oriented Concepts/Characteristics of OOPS


Object
This is the basic unit of object oriented programming. Object is the physical as
well as logical entity where as class is the only logical entity. Object: Object is a
instance of class, object has attributes and behaviors.
An Object in C++ has two characteristics:
 State(Attributes)
 Behavior
For examples dog, cat, and cow are belong to animal's class. Each object has
state and behaviors. For example a dog has state:- color, name, height, age as
well as behaviors:- barking, eating, and sleeping.

Class
When you define a class, you define a blueprint for an object. This doesn't
actually define any data, but it does define what the class name means, that is,
what an object of the class will consist of and what operations can be performed
on such an object.
Difference between Class and Object
Class Object
Class is a container which
1 collection of variables and object is a instance of class
methods.
Sufficient memory space will be allocated
No memory is allocated at the
2 for all the variables of class at the time of
time of declaration
declaration.
One class definition should For one class multiple objects can be
3
exist only once in the program. created.

Example of Object and Class


In this example, we have created a Employee class that have two data
members eid and ename. We are creating the object of the Employee class and
printing the objects value.

#include<iostream.h>
#include<conio.h>
class Employee
{
public:
int salary // data member
void sal()
{
6

cout<<"Enter salary: ";


cin>>salary;
cout<<"Salary: "<<salary;
}
};
void main()
{
clrscr();
Employee e; //creating an object of Employee
e.sal();
getch();
}

Here salary is the attribute and sal() is behavior of class employee.

Abstraction
Data abstraction refers to, providing only essential information to the outside
world and hiding their background details, i.e., to represent the needed
information in program without presenting the details.
Let's take one real life example of a TV, which you can turn on and off, change
the channel, adjust the volume, and add external components such as speakers,
VCRs, and DVD players, BUT you do not know its internal details, that is, you do
not know how it receives signals over the air or through a cable, how it translates
them, and finally displays them on the screen.
Thus, we can say a television clearly separates its internal implementation from
its external interface and you can play with its interfaces like the power button,
channel changer, and volume control without having zero knowledge of its
internals.
Now, if we talk in terms of C++ Programming, C++ classes provides great level
of data abstraction. They provide sufficient public methods to the outside world
to play with the functionality of the object and to manipulate object data, i.e.,
state without actually knowing how class has been implemented internally.

Encapsulation
Encapsulation is placing the data and the functions that work on that data in the
same place. While working with procedural languages, it is not always clear
which functions work on which variables but object-oriented programming
provides you framework to place the data and the relevant functions together in
the same object.
7

It is the mechanism that binds together code and data in manipulates, and keeps
both safe from outside interference and misuse. In short, it isolates a particular
code and data from all other codes and data.
A well-defined interface controls the access to that particular code and data. The
act of placing data and the operations that perform on that data in the same
class. The class then becomes the 'capsule' or container for the data and
operations.
Storing data and functions in a single unit (class) is encapsulation. Data cannot be
accessible to the outside world and only those functions which are stored in the
class can access it.
Inheritance
One of the most useful aspects of object-oriented programming is code
reusability. As the name suggests Inheritance is the process of forming a new
class from an existing class that is from the existing class called as base class, new
class is formed called as derived class.
This is a very important concept of object-oriented programming since this
feature helps to reduce the code size.
It is the process by which one object acquires the properties of another object.
This supports the hierarchical classification. Without the use of hierarchies, each
object would need to define all its characteristics explicitly. However, by use of
inheritance, an object need only define those qualities that make it unique within
its class. It can inherit its general attributes from its parent. A new sub-class
inherits all of the attributes of all of its ancestors
Polymorphism
The ability to use an operator or function in different ways in other words giving
different meaning or functions to the operators or functions is called
polymorphism. Poly refers to many. That is a single function or an operator
functioning in many ways different upon the usage is called polymorphism.
Polymorphism means the ability to take more than one form. An operation may
exhibit different behaviors in different instances. The behavior depends on the
data types used in the operation.
It is a feature that allows one interface to be used for a general class of actions.
The specific action is determined by the exact nature of the situation. In general,
polymorphism means "one interface, multiple methods", This means that it is
possible to design a generic interface to a group of related activities. This helps
reduce complexity by allowing the same interface to be used to specify a general
class of action. It is the compiler's job to select the specific action (that is,
method) as it applies to each situation.
Dynamic Binding

Binding refers to the process of converting identifiers (such as variable and


performance names) into addresses. Binding is done for each variable and
8

functions. For functions, it means that matching the call with the right function
definition by the compiler. It takes place either at compile time or at runtime.
Early Binding (compile-time time polymorphism) As the name indicates,
compiler (or linker) directly associate an address to the function call. It replaces
the call with a machine language instruction that tells the mainframe to leap to
the address of the function.
Late Binding : (Run time polymorphism) In this, the compiler adds code that
identifies the kind of object at runtime then matches the call with the right
function definition (Refer this for details). This can be achieved by declaring
a virtual function.
Message Passing
Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure
and therefore will invoke a function in the receiving object that generates the
desired results. Message passing involves specifying the name of the object, the
name of the function and the information to be sent.
Message Passing is passing objects as parameters (to a method)
class A
{
public void Method(Object obj)
{
// Method does somthing
}
}

class B
{
Object obj1 = new Object();

A a = new A();
a.Method1(obj1);
}
In the above example a.Method1() is Method invocation
passing parameter (obj1) to Method1 is message passing
Benefits of OOP
C+ of OOP's
 Through inheritance, we can eliminate redundant code and extend the use
of existing classes which is not possible in procedure oriented approach.
 We can build programs from the standard working modules that
communicate with one another, rather than having to start writing the
code from scratch which happens procedure oriented approach. This leads
to saving of development time and higher productivity.
9

 The principle of data hiding helps the programmer to build secure


programs that cannot be invaded by code in other parts of the program.
 It is possible to have multiple instances of object to co-exist without any
interference.
 It is possible to map objects in the problem domain to those in the
program.
 It is easy to partition the work in a project based on objects .
 The data-centered design approach enables us to capture more details of a
model in implementable from.
 Object oriented systems can be easily upgraded from small to large
systems.
 Message passing techniques for communication between objects makes
the interface descriptions with external systems much simpler.
 Software complexity can be easily managed.

Structure of c++ Program

give example

Features of c++
C++ is object oriented programming language and it is a very simple and easy
language, It is the enhanced form of C programming language. this language
have following features and here we discuss some important features of C++.
10

Important Features of C++


 Simple
 Portability
 Powerful
 Platform dependent
 Object oriented oriented
 Case sensitive
 Compiler based
 Syntax based language
 Use of Pointers
Simple
Every C++ program can be written in simple English language so that it is very
easy to understand and developed by programmer.
Portability
It is the concept of carrying the instruction from one system to another
system. In C++ Language .cpp file contain source code, we can edit also this
code. .exe file contain application, only we can execute this file. When we
write and compile any C++ program on window operating system that
program easily run on other window based system.
When we can copy .exe file to any other computer which contain window
operating system then it works properly, because the native code of
application an operating system is same.
Powerful
C++ is a very powerful programming language, it have a wide verity of data
types, functions, control statements, decision making statements, etc.
Platform dependent
A language is said to be platform dependent whenever the program is execute
in the same operating system where that was developed and compiled but not
11

run and execute on other operating system. C++ is platform dependent


language.
Object oriented Programming language
This main advantage of C++ is, it is object oriented programming language. It
follow concept of oops like polymorphism, inheritance, encapsulation,
abstraction.
Case sensitive
C++ is a case sensitive programming language. In C++ programming 'break and
BREAK' both are different.
If any language treats lower case latter separately and upper case latter
separately than they can be called as case sensitive programming language
[Example c, c++, java, .net are sensitive programming languages.] other wise it
is called as case insensitive programming language [Example HTML, SQL is
case insensitive programming languages].
Compiler based
C++ is a compiler based programming language that means without
compilation no C++ program can be executed. First we need compiler to
compile our program and then execute.
Syntax based language
C++ is a strongly tight syntax based programming language. If any language
follow rules and regulation very strictly known as strongly tight syntax based
language. Example C, C++, Java, .net etc. If any language not follow rules and
regulation very strictly known as loosely tight syntax based language.
Example HTML.
Efficient use of pointers
Pointers is a variable which hold the address of another variable, pointer
directly direct access to memory address of any variable due to this
performance of application is improve. In C++ language also concept of pointer
are available.
Advantage of C++ Programming Language
 Abstract data type defining is very good
 C++ language is efficient having less compiled time.
 It is much suitable for large projects.
 Encapsulation, polymorphism, abstraction are the important properties of
C++ language
 Objects, methods, instance, message passing, inheritance are some
important properties inherited by this language
 C++ Programming is easy to maintain and modify existing code as new
objects with small difference to existing ones.
 C++ Programming is implemented on real life scenario.
 The properties of inheritance make simple the program by complexity. Do
not required to write again.
12

 Implementation details are hidden from other modules which represent a


clearly defined interface.

Data types in c++


Data types define the type of data a variable can hold, for example an integer
variable can hold integer data, a character type variable can hold character data
etc.
Data types in C++ are categorised in three groups: Built-in, user-
defined and Derived.
Hierarchy of data types in c++

Primitive/Built_in Data Types:


These data types are built-in or predefined data types and can be used directly by
the user to declare variables. example: int, char , float, bool etc. Primitive data
types available in C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Integer: Keyword used for integer data types is int. Integers typically
requires 4 bytes of memory space and ranges from -2147483648 to
2147483647.
 Character: Character data type is used for storing characters. Keyword used
for character data type is char. Characters typically requires 1 byte of
memory space and ranges from -128 to 127 or 0 to 255.
13

 Boolean: Boolean data type is used for storing boolean or logical values. A
boolean variable can store either true or false. Keyword used for boolean
data type is bool.
 Floating Point: Floating Point data type is used for storing single precision
floating point values or decimal values. Keyword used for floating point
data type is float. Float variables typically requires 4 byte of memory space.
 Double Floating Point: Double Floating Point data type is used for storing
double precision floating point values or decimal values. Keyword used for
double floating point data type is double. Double variables typically
requires 8 byte of memory space.
 void: Void means without any value. void datatype represents a valueless
entity. Void data type is used for those function which does not returns a
value.
Derived data types in C++
Derived Data Types: Data types that are derived from the built-in data types are
known as derived data types. The various derived data types provided by C++
are arrays, junctions, references and pointers.
We have four types of derived-defined data types in C++
1. Array
2. Function
3. Pointer
4.Reference
Array An array is a set of elements of the same data type that are referred to by
the same name. All the elements in an array are stored at contiguous (one after
another) memory locations and each element is accessed by a unique index or
subscript value. The subscript value indicates the position of an element in an
array. To declare an array in C++, the programmer specifies the type of the
elements and the number of elements required by an array as follows −
type arrayName [ arraySize ];

This is called a single-dimension array. The arraySize must be an integer


constant greater than zero and type can be any valid C++ data type. For
example, to declare a 10-element array called A of type int, use this
statement −
int A[10];

Function A function is a self-contained program segment that carries out a


specific well-defined task. In C++, every program contains one or more functions
which can be invoked from other parts of a program, if required.
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}
14

Reference A reference is an alternative name for a variable. That is, a reference is


an alias for a variable in a program. A variable and its reference can be used
interchangeably in a program as both refer to the same memory location. Hence,
changes made to any of them (say, a variable) are reflected in the other (on a
reference). For example, suppose we have the following example −
int i = 17;

We can declare reference variables for i as follows.


int& r = i;

Read the & in these declarations as reference. Thus, read the first
declaration as "r is an integer reference initialized to i"
Following example makes use of references
#include <iostream.h>
int main () {
// declare simple variables
int i;
// declare reference variables
int& r = i;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
return 0;
}

Pointer A pointer is a variable that can store the memory address of another
variable. Pointers allow to use the memory dynamically. That is, with the help of
pointers, memory can be allocated or de-allocated to the variables at run-time,
thus, making a program more efficient. The general form of a pointer variable
declaration is −
type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-
name is the name of the pointer variable. the asterisk is being used to
designate a variable as a pointer. Following are the valid pointer declaration

int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

The actual data type of the value of all pointers, whether integer, float,
character, or otherwise, is the same, a long hexadecimal number that
represents a memory address.
User-defined data types
We have four types of user-defined data types in C++
1. struct
2. union
3. Enum
4. class
15

Struct In C++ language Array is also a user defined data type but Array hold or
store only similar type of data, If we want to store different-different type of data.
In this case we need to defined separate variable for each type of data. To resolve
this problem we use Structure in C++ Programming, It can store different-different
data type in single variable. Example: Suppose we want to store Student
record, then we need to store....
 Student Name
 Roll number
 Class
 Address
For store Student name and Address we need character data type, for
store Roll number and class we need integer data type.
If we use Structure then we use single variable for all data like belowe
example.
Example

struct stu
{
char student_name[10];
char address[20];
int roll_no[5];
int class[5];
};

Union
A union is a special data type available in C that allows storing different data types in
the same memory location. You can define a union with many members, but only one
member can contain a value at any given time. Unions provide an efficient way of using
the same memory location for multiple purposes.
Defining a Union: To define a union, you must use the unionstatement in the same way
as you did while defining a structure. The union statement defines a new data type with
more than one member for your program. The format of the union statement is as
follows:
union [union name]
{
member definition;
member definition;
...
member definition;
};

Enum
An enumeration is a user-defined data type that consists of integral constants. To define
an enumeration, keyword enum is used.

enum season { spring, summer, autumn, winter };

Here, the name of the enumeration is season.


And, spring, summer and winter are values of type season.
By default, spring is 0, summer is 1 and so on.
16

class
A class is used to specify the form of an object and it combines data
representation and methods for manipulating that data into one neat package.
The data and functions within a class are called members of the class. A class
definition starts with the keyword class followed by the class name; and
the class body, enclosed by a pair of curly braces. A class definition must be
followed either by a semicolon or a list of declarations. For example, we
defined the Box data type using the keyword class as follows −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

The keyword public determines the access attributes of the members of


the class that follows it. A public member can be accessed from outside the
class anywhere within the scope of the class object. You can also specify
the members of a class as private or protected which we will discuss in a
sub-section.
Operators in c++
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators and
provide the following types of operators −
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
Types of Operators in C++

1) Basic Arithmetic Operators


Basic arithmetic operators are: +, -, *, /, %
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200


17

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an B % A will give 0


integer division

++ Increment operator, increases integer A++ will give 11


value by one

-- Decrement operator, decreases integer A-- will give 9


value by one

2) Assignment Operators
Assignments operators in C++ are: =, +=, -=, *=, /=, %=
There are following assignment operators supported by C++ language −
Show Examples
Operator Description Example

= Simple assignment operator, Assigns values


C = A + B will assign value
from right side operands to left side
of A + B into C
operand.

+= Add AND assignment operator, It adds right


C += A is equivalent to C =
operand to the left operand and assign the
C+A
result to left operand.

-= Subtract AND assignment operator, It


subtracts right operand from the left C -= A is equivalent to C =
operand and assign the result to left C-A
operand.

*= Multiply AND assignment operator, It


multiplies right operand with the left C *= A is equivalent to C =
operand and assign the result to left C*A
operand.

/= Divide AND assignment operator, It divides


C /= A is equivalent to C =
left operand with the right operand and
C/A
assign the result to left operand.

%= Modulus AND assignment operator, It takes


C %= A is equivalent to C =
modulus using two operands and assign the
C%A
result to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C


<< 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C


>> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C &


2

^= Bitwise exclusive OR and assignment C ^= 2 is same as C = C ^


operator. 2
18

|= Bitwise inclusive OR and assignment


C |= 2 is same as C = C | 2
operator.

3) Logical Operators
Logical Operators are used with binary variables. They are mainly used in
conditional statements and loops for evaluating a condition.
Logical operators in C++ are: &&, ||, !
Assume variable A holds 1 and variable B holds 0, then −
Show Examples
Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then condition
becomes true.

! Called Logical NOT Operator. Use to !(A && B) is true.


reverses the logical state of its operand. If a
condition is true, then Logical NOT operator
will make false.

4) Relational operators
We have six relational operators in C++: ==, !=, >, <, >=, <=
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Operator Description Example

== Checks if the values of two operands are (A == B) is not true.


equal or not, if yes then condition becomes
true.

!= Checks if the values of two operands are (A != B) is true.


equal or not, if values are not equal then
condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand, if
yes then condition becomes true.

< Checks if the value of left operand is less (A < B) is true.


than the value of right operand, if yes then
condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of right
operand, if yes then condition becomes
true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right operand,
if yes then condition becomes true.
19

5) Bitwise Operators
There are six bitwise Operators: &, |, ^, ~, <<, >>
Operator Description Example

& Binary AND Operator copies a bit to the (A & B) will give 12 which
result if it exists in both operands. is 0000 1100

| Binary OR Operator copies a bit if it exists (A | B) will give 61 which


in either operand. is 0011 1101

^ Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which


set in one operand but not both. is 0011 0001

~ Binary Ones Complement Operator is unary (~A ) will give -61 which
and has the effect of 'flipping' bits. is 1100 0011 in 2's
complement form due to a
signed binary number.

<< Binary Left Shift Operator. The left


A << 2 will give 240
operands value is moved left by the number
which is 1111 0000
of bits specified by the right operand.

>> Binary Right Shift Operator. The left


operands value is moved right by the A >> 2 will give 15 which
number of bits specified by the right is 0000 1111
operand.

6) Misc Operators Operator


The following table lists some other operators that C++ supports.
Sr.No Operator & Description

1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a),
where ‘a’ is integer, and will return 4.

2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X
otherwise returns value of Y.

3 ,
Comma operator causes a sequence of operations to be performed. The
value of the entire comma expression is the value of the last expression of
the comma-separated list.

4 . (dot) and -> (arrow)


Member operators are used to reference individual members of classes,
structures, and unions.

5 Cast
Casting operators convert one data type to another. For example,
int(2.2000) would return 2.
20

6 &
Pointer operator & returns the address of a variable. For example &a; will
give actual address of the variable.

7 *
Pointer operator * is pointer to a variable. For example *var; will pointer
to a variable var.

sizeof operator
The sizeof is a keyword, but it is a compile-time operator that determines the
size, in bytes, of a variable or data type.
The sizeof operator can be used to get the size of classes, structures, unions and
any other user defined data type.
The syntax of using sizeof is as follows −
sizeof (data type)
Where data type is the desired data type including classes, structures, unions and
any other user defined data type.
member operator
The . (dot) operator and the -> (arrow) operator are used to reference individual
members of classes, structures, and unions.
The dot operator is applied to the actual object. The arrow operator is used with
a pointer to an object. For example, consider the following structure −
struct Employee {
char first_name[16];
int age;
} emp;
The (.) dot operator
To assign the value "zara" to the first_name member of object emp, you would
write something as follows −
strcpy(emp.first_name, "zara");
The (->) arrow operator
If p_emp is a pointer to an object of type Employee, then to assign the value
"zara" to the first_name member of object emp, you would write something as
follows −
strcpy(p_emp->first_name, "zara");
The -> is called the arrow operator. It is formed by using the minus sign followed
by a greater than sign.
comma operator
The purpose of comma operator is to string together several expressions. The
value of a comma-separated list of expressions is the value of the right-most
21

expression. Essentially, the comma's effect is to cause a sequence of operations


to be performed.
The values of the other expressions will be discarded. This means that the
expression on the right side will become the value of the entire comma-
separated expression. For example −
var = (count = 19, incr = 10, count+1);
Here first assigns count the value 19, assigns incr the value 10, then adds 1 to
count, and finally, assigns var the value of the rightmost expression, count+1,
which is 20. The parentheses are necessary because the comma operator has a
lower precedence than the assignment operator.
scope resolution operator
Scope resolution operator (::) in C++ programming language is used to
define a function outside a class or when we want to use a global variable
but also has a local variable with the same name.
1) To access a global variable when there is a local variable with same name:
int x; // Global x

int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Output:
Value of global x is 0
Value of local x is 10

2) To define a function outside a class.


#include<iostream>
class A
{
public:
void fun();
};

// Definition outside class using ::


void A::fun()
{
cout << "fun() called";
}

int main()
{
A a;
a.fun();
return 0;
}

Operators Precedence in C++


22

Operator precedence determines the grouping of terms in an expression. This


affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
higher precedence than +, so it first gets multiplied with 3*2 and then adds into
7.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
Show Examples
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


23

Inline function
C++ inline function is powerful concept that is commonly used with
classes. If a function is inline, the compiler places a copy of the code of that
function at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once
again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler
can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
Following is an example, which makes use of inline function to return max
of two numbers −
#include <iostream>
inline int Max(int x, int y) {
return (x > y)? x : y;
}

// Main function for the program


int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0;
}

Remember, inlining is only a request to the compiler, not a command. Compiler can
ignore the request for inlining. Compiler may not perform inlining in such circumstances
like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist in
function body.
5) If a function contains switch or goto statement.
Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of calling
context and the called context.
5) Inline function may be useful (if it is small) for embedded systems because inline can
yield less code than the function call preamble and return.
Inline function disadvantages:
1) The added variables from the inlined function consumes additional registers, After in-
lining function if variables number which are going to use register increases than they
may create overhead on register variable resource utilization. This means that when
inline function body is substituted at the point of function call, total number of variables
24

used by the function also gets inserted. So the number of register going to be used for
the variables will also get increased. So if after function inlining variable numbers
increase drastically then it would surely cause an overhead on register utilization.
2) If you use too many inline functions then the size of the binary executable file will be
large, because of the duplication of same code.
3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the
speed of instruction fetch from that of cache memory to that of primary memory.
4) Inline function may increase compile time overhead if someone changes the code
inside the inline function then all the calling location has to be recompiled because
compiler would require to replace all the code once again to reflect the changes,
otherwise it will continue with old functionality.
5) Inline functions may not be useful for many embedded systems. Because in
embedded systems code size is more important than speed.
6) Inline functions might cause thrashing because inlining might increase size of the
binary executable file. Thrashing in memory causes performance of computer to
degrade.

Difference between inline and simple function

The distinction between normal functions and inline functions is the


different compilation process for them.
After writing any program, it is first compiled to get an executable code. Which is then
executed, the OS loads the instructions into the computer's memory, so that each
instruction is stored in a specific memory location. When a function call
instruction is encountered, the compiler stores the memory address of the
instruction immediately following the function call statement, loads the function
being called into the memory, copies argument values, jumps to the memory location of
the called function, executes the function code, stores the return value of the function,
and then jumps back to the address of the instruction that was saved just before
executing the called function.
The C++ inline function provides an alternative. With inline code, the compiler
replaces the function call statement with the function code itself (this
process is called expansion) and then compiles the entire code. Thus, with this the
compiler doesn't have to do the long, time consuming process.
Main Advantage of Inline Functions : They save on overheads of a function call as
it's not invoked, rather its code is replaced in the program.
Main Disadvantage of Inline Functions : With more function calls (for ex: in a
loop), the repeated occurrences of same function code wastes memory space.
The syntax for defining the normal function is:
return-type function-name(parameters)
{
// function code
}
The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
example of normal function
#include <iostream>
inline int cube(int s)
{
return s*s*s;
25

}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n"; //call is replaced by 3*3*3
return 0;
} //Output: The cube of 3 is: 27
Example of inline function
#include <iostream>
int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
} //Output: The cube of 3 is: 27

String and string manipulation functions


C++ provides following two types of string representations −
 The C-style character string.
 The string class type introduced with Standard C++.

The C-Style Character String


The C-style character string originated within the C language and continues
to be supported within C++. This string is actually a one-dimensional array
of characters which is terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise the string followed
by a null.
The following declaration and initialization create a string consisting of the
word "Hello". To hold the null character at the end of the array, the size of
the character array containing the string is one more than the number of
characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above
statement as follows −
char greeting[] = "Hello";

Following is the memory presentation of above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant.
The C++ compiler automatically places the '\0' at the end of the string
when it initializes the array. Let us try to print above-mentioned string −
26

#include <iostream>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}
When the above code is compiled and executed, it produces the following
result −
Greeting message: Hello

C++ supports a wide range of functions that manipulate null-terminated


strings −
Sr.No Function & Purpose

1 strcpy(s1, s2);
Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than 0 if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in
string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in
string s1.
Following example makes use of few of the above-mentioned functions −

#include <iostream>
#include <cstring>
int main () {

char str1[10] = "Hello";


char str2[10] = "World";
char str3[10];
int len ;
// copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
// concatenates str1 and str2
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
// total lenghth of str1 after concatenation
len = strlen(str1);
27

cout << "strlen(str1) : " << len << endl;


return 0;
}
When the above code is compiled and executed, it produces result
something as follows −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

The String Class in C++


The standard C++ library provides a string class type that supports all the
operations mentioned above, additionally much more functionality. Let us
check the following example −
#include <iostream>
#include <string>
int main () {

string str1 = "Hello";


string str2 = "World";
string str3;
int len ;
// copy str1 into str3
str3 = str1;
cout << "str3 : " << str3 << endl;
// concatenates str1 and str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
// total length of str3 after concatenation
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}
When the above code is compiled and executed, it produces result
something as follows −
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
28
29

UNIT-2

Access modifiers
Data hiding is one of the important features of Object Oriented Programming
which allows preventing the functions of a program to access directly the
internal representation of a class type. The access restriction to the class
members is specified by the labeled public, private, and protected sections
within the class body. The keywords public, private, and protected are called
access specifiers.
A class can have multiple public, protected, or private labeled sections. Each
section remains in effect until either another section label or the closing right
brace of the class body is seen. The default access for members and classes is
private.
class Base {

public:

// public members go here

protected:

// protected members go here

private:

// private members go here

};
The public members:
A public member is accessible from anywhere outside the class but within a
program. You can set and get the value of public variables without any member
function as shown in the following example:

class abc
{
public: // public access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
};
Void main()
{
Abc o1;
30

O1.x=10; //valid
O1.diplay();//valid
}

private members:
A private member variable or function cannot be accessed, or even viewed from
outside the class. Only the class and friend functions can access private members.
class abc
{
private: // private access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
};
Void main()
{
Abc o1;
O1.x=10; //invalid
O1.diplay();//invalid
}

The protected members:


A protected member variable or function is very similar to a private member but
it provided one additional benefit that they can be accessed in child classes
which are called derived classes.
class abc
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function decaration
};
Void main()
{
Abc o1;
O1.x=10; //invalid
O1.diplay();//invalid
}

Dynamic memeory allocation


C++ program is divided into two parts:
 The stack: All variables declared inside the function will take up memory
from the stack.
31

 The heap: This is unused memory of the program and can be used to
allocate the memory dynamically when program runs.

Many times, you are not aware in advance how much memory you will need to
store particular information in a defined variable and the size of required
memory can be determined at run time.
You can allocate memory at run time within the heap for the variable of a given
type using a special operator in C++ which returns the address of the space
allocated. This operator is called new operator.
If you are not in need of dynamically allocated memory anymore, you can
use delete operator, which de-allocates memory previously allocated by new
operator.

new and delete operators:


There is following generic syntax to use new operator to allocate memory
dynamically for any data-type.
new data-type;
Here, data-type could be any built-in data type including an array or any user
defined data types include class or structure. Let us start with built-in data types.
For example we can define a pointer to type double and then request that the
memory be allocated at execution time. We can do this using the new operator
with the following statements:
int* pvalue = NULL; // Pointer initialized with null
pvalue = new int; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had been
used up.
At any point, when you feel a variable that has been dynamically allocated is not
anymore required, you can free up the memory that it occupies in the free store
with the delete operator as follows:
delete pvalue;
Let us put above concepts and form the following example to show how new and
delete work:
#include <iostream>
using namespace std;

int main ()
{
int* pvalue = NULL; // Pointer initialized with null
pvalue = new int; // Request memory for the variable

*pvalue = 290; // Store value at allocated address


32

cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

return 0;
}
this pointer
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member
functions. Therefore, inside a member function, this may be used to refer to the
invoking object.
The ‘this’ pointer is passed as a hidden argument to all nonstatic member
function calls and is available as a local variable within the body of all nonstatic
functions. ‘this’ pointer is a constant pointer that holds the memory address of
the current object. ‘this’ pointer is not available in static member functions as
static member functions can be called without any object
Friend functions do not have a this pointer, because friends are not members of
a class. Only member functions have a this pointer.
#include<iostream>
using namespace std;

/* local variable is same as a member's name */


class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;}
33

UNIT-4
Exception Handling
Exception handling is a programming language construct designed to handle the
occurrence of exceptions, special conditions that change the normal flow of
program execution.
Purpose
The purpose of exception handling is to provide means to detect and
report an exceptional circumstance so that appropriate action can be
taken.
 Exceptions are erroneous events like a division be zero, an arithmetic or
array overflow and exhaustion of free heap space which occur at runtime.
 In case these errors are not trapped they cause abrupt halt, without any
indication to the user about what happened
 The C++ language provides Type-safe integrated approach, for coping with
the anomalous situations that arise while executing a program called
exceptions
Types of Exceptions
 Synchronous exceptions:
◦ That occur during runtime and can be generated using the throw
expression.
◦ Only these type of errors can be handled using exception handlers in
C++.
◦ Control does not come back to the point from where the exception is
thrown. E.g. Errors like “out of range Index” and “overflow”
 Asynchronous exceptions:
◦ That occur due to keyboard or mouse interrupt.
◦ C++ programs cannot directly handle these types of exceptions using
the try and catch statements.
◦ A separate handler that automatically calls the routine associated
with the keyboard and mouse interrupts has to be created
Exception handling mechanism
 It includes a separate error handling code that performs following tasks
◦ Find the problem (Hit the exception)
◦ Inform that an error has occurred(Throw the exception)
◦ Receive the error information(Catch the exception)
◦ Take corrective actions (Handle the exception
Mechanism
 try Block: A demarcated block of program statements used to preface a
block of statements which may generate exceptions. It is also called the
guarded section
 throw: An expression called throw, which indicates to the program to jump
to statements at another location. This location in the program should be
34

an exception handler. The throw keyword followed by a value, such as


character string or an object, indication the nature of the exception
 catch handlers: A set of functions known as catch handlers, which are
executed when an exception occurs. The catch block catches the exception
thrown by the throw statement in the try block and handles it properly.

Relationship between try, throw and catch

Syntax
try
{
…………. //Block of statements which detect and throw
exception
throw exception;
}
catch (type arg) //catches exception
{
// block of statement that handles the exception of type
specified
……..
}
The try, throw and catch mechanism
 The execution of program containing the try, catch and throw statements
proceeds as follows
 The control reaches the try statement by normal sequential execution. The
guarded section within the try block is executed.
 If no exception is thrown during the execution of guarded section, the catch
clauses following the try block are not executed. Execution continues from
the statement after the last catch clause following the try block in which
exception was thrown.
 If an exception occurs, the program searches for a catch clause that can
handle the exception of the type thrown.
 If a matching handler is not found, the predefined runtime handler
terminate() is called.
35

 If a matching handler is found, its parameter is initialized and the


instructions in the catch-handler are executed

Throwing mechanism
 When an exception that is desired to be handled is detected, it is thrown
using the throw statement in one of the following forms
◦ throw(exception);
◦ throw exception;
◦ throw; //used for rethrowing an exception
 The operand exception may be of any type including constants.
 When an exception is thrown, it will be caught by the catch statement
associated with the try block i.e. control exits the current try block and is
transferred to catch block after the try block.
Catching mechanism
 Syntax for catch block
catch(type arg)
{
//statements for managing exceptions
}
type indicates the type of exceptions that catch block handles. The catch
statement catches an exception whose type matches with the type of catch
statement. When it is caught code in the catch block is executed
Multiple catch blocks
Syntax
try
{
//try block
}
catch(type1 arg)
{
//catch block 1
}

catch(type2 arg)
{
//catch block 1
}
catch(typeN arg)
{
//catch block N
}
• When exception is thrown, the exception handlers are searched in order for
an appropriate match.
36

• The first handler that yield a match is executed.


• After executing the handler the control goes to the first statement after the
last catch block for that try.
• When no match is found program is terminated
catch all exceptions
 In some situations we may not be able to anticipate all possible types of
exceptions and therefore may not be able to design independent catch
handlers to catch them.
 In such circumstances we can force a catch statement to catch all
exceptions instead of certain type alone. This can be achieved by defining
the catch statement using ellipses
Syntax
catch(…)
{
// statements for processing all exceptions
}

Rethrowing an Exception
 A handler may rethrow the exception without processing it.
 In such cases we may use the throw statement without parameters
It is also possible to nest try-catch blocks within more external try blocks. In these
cases, we have the possibility that an internal catch block forwards the exception
to its external level. This is done with the expression throw; with no arguments.
For example:
1 try {
2 try {
3 // code here
4 }
5 catch (int n) {
6 throw;
7 }
8 }
9 catch (...) {
10 cout << "Exception occurred";
11 }

void div(int x, int y) int main()


{ {
cout<<"\n Inside div Function"; Int i=90,j=9;
try try
{ {
if(y==0) div(i,j);
37

throw y; cout<<"\n Div called again with 0";


else div(0,0);
cout<<"\nDiv:"<<x/y<<endl; }
} catch(int)
catch(int) {
{ cout<<"\n Caught in main ";
cout<<"\nCaught inside }
function:"; cout<<"\nMain Ends";
throw; getch();
} return 0;
cout<<endl<<"End"; }
}

Exceptions & Inheritance


It is possible to throw classes as exceptions, and classes can be derived from other
classes
class Base class Base
{ {
public: public:
Base() {} Base() {}
}; };
class Derived: public Base class Derived: public Base
{ {
public: public:
Derived() {} Derived() {}
}; };
int main()
{ int main()
try {
{ try
throw Derived(); {
} throw Derived();
catch (Base &cBase) }
{ catch (Derived
cerr << "caught Base"; &cDerived)
} {
catch (Derived &cDerived) cerr << "caught
{ Derived";
cerr << "caught Derived"; }
} catch (Base &cBase)
return 0; {
} cerr << "caught Base";
38

In the above example we throw an exception of }


type Derived. However, the output of this
program is: return 0;
caught Base
Explanation This way, the Derived
 The derived classes will be caught by handler will get first shot at
handlers for the base type. catching objects of type
 Because Derived is derived from Base, Derived (before the handler
Derived is-a Base (they have an is-a for Base can). Objects of
relationship). type Base will not match
 Second, when C++ is attempting to find a the Derived handler
handler for a raised exception, it does so (Derived is-a Base, but Base
sequentially. is not a Derived), and thus
 Consequently, the first thing C++ does is will “fall through” to the
check whether the exception handler for Base handler.
Base matches the Derived exception.  Rule: Handlers for
 Because Derived is-a Base, the answer is derived exception
yes, and it executes the catch block for classes should be listed
type Base! before those for base
 The catch block for Derived is never even classes
tested in this case.

Templates

Templates are a feature of the C++ programming language that allow functions
and classes to operate with generic types.
It enables us to define generic classes and functions and provide support for
generic programming.
Templates are blueprints of a function or a class that can be applied to different
data types.
The essence of templates as the instantiation of functions and the classes
themselves at runtime according to requirements. This means that the programar
does not have to know the exact utilization context at the coding stage. The end
user can create user defined classes at the time of implementation. A template
may be considered a type of macro. When an object of a specific type is defined
for actual use, the template definition for that class is substituted with the
required data type. Since a template is defined with a parameter that would be
replaced by a specified data type at the time of actual use of the class or function,
the templates are some times called parametrized classes or functions.
39

Template Class/Generic Class:


A template class may be defined as the layout and operations for an unbounded
set of related classes. Built-in data types can be given as template arguments in
the list for a template class
Syntax
template <class T1>
class classname
{
//public
T1 var;
};
Example
#include<iostream.h>
#include<conio.h>
template<class T>
class xyz
{
public :
T a;
xyz(T x)
{
a=x;
cout<<"\na="<<a;
}
};
int main()
{
xyz<int> o1(10);
xyz<float> o2(10.45);
getch();
return 0;
}
Output
a=10
a=10.45

Class template with multiple parameters


We can use more than one generic data type in a class template.
The syntax is
Syntax
template <class T1,class T2>
class classname
40

{
//public
T1 var1;
T2 var2;
};
Example
#include<iostream.h>
#include<conio.h>
template<class T1,class T2>
class xyz
{
public :
T1 a;
T2 b;
xyz(T1 x, T2 y)
{
a=x;
b=y;
cout<<"\na="<<a;
cout<<”\nb=”<<b;
}
};
int main()
{
xyz<int,int> o1(10,20);
xyz<float,float> o2(10.45,2,5);
xyz<int,float> o3(10,20.8);
xyz<float,int> o1(10.8,20);
getch();
return 0;
}
Template function/Generic function:
A template function may be defined as an unbounded set of overloaded
functions. This means that all the possible parameters to the function are not
known in advance and a copy of function has to be created as and when
necessary.
Template functions are created using the keyword template.
Syntax
Template<class T1, class T2, >
void function_name(T1 parameter1, T2 parameter 2)
{
...
41

}
Example
#include<iostream.h>
#include<conio.h>
template<class T>
T max(T a, T b)
{ return a>b?a:b;
}
int main()
{
cout<<"\nmax('A','a')="<<max('A','a');
cout<<"\nmax(5,3)="<<max(5,3);
cout<<"\nmax(14.2,14.02)="<<max(14.2,14.02);
getch();
return 0;
}
Overloading of templates
 Template function may be overloaded either by template function or
ordinary function of its name
 Resolution is accomplished as follows
◦ Call an ordinary function that has an exact match
◦ Call a template that could be created with an exact match
◦ Try normal overloading resolution to ordinary functions and call the
one that matches
template <class T>
void display(T x)
{
cout<<"Template Display:"<<x<<"\n";
}
void display(int x)
{
cout<<"explicit Display:"<<x<<"\n";
}
void display(char x)
{
cout<<"explicit Display:"<<x<<"\n";
}
int main()
{
display(100);
display(23.4);
42

display('f');
getch();
}
OUTPUT
Explicit display 100
Template display 23.4
Explicit display f

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy