SlideShare ist ein Scribd-Unternehmen logo
1 von 34
UNIT III
Overloading
09/04/131 VIT - SCSE
By
G.SasiKumar., M.E., (Ph.D).,
Assistant Professor
School of Computing Science and Engineering
VIT University
Functions in C++
Experience has shown that the best way to develop and
maintain large programs is to construct it from smaller pieces
(Modules)
This technique Called “Divide and Conquer”
‱Easer To
Design
Build
Debug
Extend
Modify
Understand
Reuse
Better Organization
Wise Development Approach
main()
{
-----
----
}
function f1()
{
---
---
}
function f2()
{
---
---
}
Function Overloading
C++ supports writing more than one function with the same
name but different argument lists. This could include:
different data types
different number of arguments
The advantage is that the same apparent function can be
called to perform similar but different tasks. The following
will show an example of this.
Function Overloading
void swap (int *a, int *b) ;
void swap (float *c, float *d) ;
void swap (char *p, char *q) ;
int main ( )
{
int a = 4, b = 6 ;
float c = 16.7, d = -7.89 ;
char p = 'M' , q = 'n' ;
swap (&a, &b) ;
swap (&c, &d) ;
swap (&p, &q) ;
}
void swap (int *a, int *b)
{ int temp; temp = *a; *a =
*b; *b = temp; }
void swap (float *c, float *d)
{ float temp; temp = *c; *c =
*d; *d = temp; }
void swap (char *p, char *q)
{ char temp; temp = *p; *p
= *q; *q = temp; }
09/04/135 VIT - SCSE
‱ Operator Overloading refers to giving the normal C++ Operators,
such as +,*,<= etc., additional meanings when they are applied
to user defined data types.
‱ Simply defined as to create new definitions for operators.
Syntax :
<ret.datatype> operator <operator name>()
{
---
---
}
Operator Overloading
The steps involved an operator are :
1. Create a class that defines a data type that is to be
used in the overloading operation
2. Declare the operator function as either a member
function or a friend function inside the class
3. Define the operator function either inside or outside
the class
4. Use the operator in the main() function
‱ All the operators can be overloaded using friend
function except () [] -> and =. These operators must be
defined by using a member function.
ASSIGNMENT OPERATOR OVERLOADING RULES :
‱ The operator function for the assignment operator are
inherited by any derived class.
‱ Friend functions cannot be used to overload the
assignment operator
The operators that can be overloaded
are
+ - * / % ^ &
| _ != < > <= >= +=
-+ *= != ++ -- [ ] ()
|| &= && -> , new delete
The operators that cannot be overloaded are
#
.(member operator)
::
sizeof
?:
09/04/139 VIT - SCSE
class sample
{
private:
int x;
float y;
public:
sample(int,float);
void operator =(sample s);
void display();
};
sample::sample(int one,float
two)
{
x=one;
y=two;
}
void sample::operator =(sample s)
{
x=s.x;
y=s.y;
}
void sample::display()
{
cout<<”integer
number(x)=:”<<x<<endl;
cout<<”floating
value(y)=:”<<y<<endl;
cout<<endl;
}
(Unary)Overloading Assignment Operator (=)
09/04/1310 VIT - SCSE
void main()
{
sample ob1(10,4.5);
sample ob2(20,6.2);
ob1=ob2;
cout<<”contents of the first object n”;
ob1.display();
cout<<”contents of the second object n”;
ob2.display();
}
09/04/1311 VIT - SCSE
class sample
{
private :
int x;
public :
sample()
{
x=0;
}
int getcount()
{
return x;
}
sample operator ++()
{
++x;
sample t;
t.x=x;
return t;
}};
void main()
{
sample s1,s2;
cout<<"s1
="<<s1.getcount()<<endl;
cout<<"s2
="<<s2.getcount()<<endl;
++s1;
s2=++s1;
cout<<"s1
="<<s1.getcount()<<endl;
cout<<"s2
="<<s2.getcount()<<endl;
getch();
}
Overloading ++ Operator
OUTPUT :
s1 = 0
s2 = 0
s1 = 2
s2 = 2
09/04/1312 VIT - SCSE
class sample
{
private:
int x;
public:
sample();
sample(int);
sample operator +(sample
s);
void display();
};
sample::sample()
{
x=0;
}
sample::sample(int one)
{
x=one;
}
sample sample::operator +
(sample s)
{
sample t;
t.x=x+s.x;
return(t);
}
void sample::display()
{
cout<<”X=”<<x<<endl;
}
(Binary) Overloading Arithmetic Operators (+)
09/04/1313 VIT - SCSE
void main()
{
sample ob1(10);
sample ob2(20);
sample ob3;
ob3=ob1+ob2;
ob1.display();
ob2.display();
ob3.display();
} OUTPUT :
X=10
X=20
X=30
09/04/1314 VIT - SCSE
class sample
{
private:
int x;
public:
sample();
sample(int);
sample operator -(sample
s);
void display();
};
sample::sample()
{
x=0;
}
sample::sample(int one)
{
x=one;
}
sample sample::operator -
(sample s)
{
sample t;
t.x=x-s.x;
return(t);
}
void sample::display()
{
cout<<”X=”<<x<<endl;
}
(Binary) Overloading Arithmetic Operators (-)
09/04/1315 VIT - SCSE
void main()
{
sample ob1(10);
sample ob2(20);
sample ob3;
ob3=ob1-ob2;
ob1.display();
ob2.display();
ob3.display();
} OUTPUT :
X=10
X=20
X=-10
#include<iostream.h>
const int SIZE=5;
class test
{
private :
int a[SIZE];
public:
int operator [] (int i)
{
return i;
}
};
void main()
{
test t1;
int i;
OVERLOADING THE SUBSRIPTOPERATOR [ ]
for(i=1;i<=SIZE;i++)
{
// control is transferred to the operator
function call int operator [] (int i)
cout<<t1[i]<<"t";}
}
OUTPUT :
1
2
3
4
5
09/04/1317 VIT - SCSE
class sample
{
private:
int x;
public:
sample();
sample(int one);
void display();
int operator <(sample s);
};
sample::sample()
{
x=0;
}
sample::sample(int one)
{
x=one;
}
void sample::display()
{
cout<<"X="<<x<<endl;
}
int sample::operator <(sample s)
{
return (x<s.x);
}
void main()
{
sample ob1(20);
sample ob2(100);
cout<<(ob1<ob2)<<endl;
cout<<(ob2<ob1)<<endl;
getch();
}
Overloading Arithmetic Comparison Operators (<)
OUTPUT :
1
0
09/04/1318 VIT - SCSE
class sample
{
private:
int x;
public:
sample();
sample(int);
sample operator +=(sample s);
void display();
};
sample::sample()
{
x=0;
}
sample::sample(int one)
{
x=one;
}
sample sample::operator +=(sample s)
{
return(x+=s.x);
}
void sample::display()
{
cout<<"X="<<x<<endl;
}
void main()
{
sample ob1(10);
sample ob2(20);
ob1.display();
ob2.display();
ob2+=ob1;
ob1.display();
ob2.display();
}
Overloading Compound Assignment Operator (+=)
OUTPUT :
X=10
X=20
X=10
X=30
09/04/1319 VIT - SCSE
class sample
{
private:
int x;
public:
sample();
sample(int one);
void display();
int operator <=(sample s);
};
sample::sample()
{
x=0;
}
sample::sample(int one)
{
x=one;
}
void sample::display()
{
cout<<"X="<<x<<endl;
}
int sample::operator <=(sample s)
{
return (x<=s.x);
}
void main()
{
sample ob1(20);
sample ob2(100);
cout<<(ob1<=ob2)<<endl;
cout<<(ob2<=ob1)<<endl;
getch();
}
Overloading Compound Assignment Operator (<=)
OUTPUT :
1
0
Increment and Decrement Operators
We have used n++; and ++n; to replace for n = n + 1;
and we have used --n and n--; to replace for n = n - 1;
The expressions n++ and ++n have values.
The expression n++ returns the value of n before to
incrementing, then increments the value of n.
++n increments the value of n, then returns the
incremented value.
The expressions n-- and --n have values as well.
The expression n-- returns the value of n before to
decrementing, then decrements the value of n.
--n decrements the value of n, then returns the decremented
value.
Overloading ++ and - -
With C++, you use ++ to increment variables, and - -
to decrement variables
When a prefix operator such as ++ is used in an
expression, the mathematical operation takes place
before the expression is evaluated
When the postfix operator is used, the expression is
evaluated before the mathematical operation takes
place
Using the Prefix and Postfix ++
Operators with an Integer
Generic Programming for Templates
A methodology for the development of reusable software
libraries
Three primary tasks:
Categorize the abstractions in a domain into concepts
Implement generic algorithms based on the concepts
Build concrete models of the concepts
Concepts make templates easier to use
Express requirements directly in code
Provide complete type-checking of templates
Characteristics of Generic Libraries
Reusable: able to operate on user-defined data types
Composable: able to operate on data types defined in
another library
Efficient: performance on par with non-generic, hand-
coded implementations
C++ Templates
 C++ Function Templates
-- C++ Function templates are those functions which can
handle different data types without separate code for each of
them. 
 C++ Class Templates
-- C++ Class Templates are used where we have multiple
copies of code for different data types with the same logic.
Templates
Constructs a family of related functions or class
Different Approach – Function
  
Example 1 & 2 : int Add(int a,int b) { return a+b;} // function Without C++ template
float Add(float a, float b) { return a+b;} // function Without C++ template
1. NaĂŻve Approach
Different Function Definitions
Different Function Names
2. Function Overloading
Different Function Definitions
Same Function Name
3. Template Functions
One Function Definition (a function template)
Compiler Generates Individual Functions
Approach 3: Function Template
‱ A C++ language construct that allows the compiler
to generate multiple versions of a function by
allowing parameterized data types.
Template < TemplateParamList >
FunctionDefinition
FunctionTemplate
TemplateParamDeclaration: placeholder
class typeIdentifier
typename variableIdentifier
Example of a Function Template
template<class T>
T Add(T a,T b)//C++ Fucntion Template sample
{
return a+b;
}
Template parameter
(class, user defined
type, built-in types)
Class Template
‱ A C++ language construct that allows the compiler
to generate multiple versions of a class by allowing
parameterized data types.
Template < TemplateParamList >
ClassDefinition
Class Template
TemplateParamDeclaration: placeholder
class typeIdentifier
typename variableIdentifier
Example of a Class Template
template<class ItemType>
class GList
{
public:
bool IsEmpty() const;
bool IsFull() const;
int Length() const;
void Insert( /* in */ ItemType item );
void Delete( /* in */ ItemType item );
bool IsPresent( /* in */ ItemType item ) const;
void SelSort();
void Print() const;
GList(); // Constructor
private:
int length;
ItemType data[MAX_LENGTH];
};
Template
parameter
Advantages of C++ Class Templates: 
One C++ Class Template can handle different types of
parameters.
Compiler generates classes for only the used types. If the
template is instantiated for int type, compiler generates only
an int version for the c++ template class.
Templates reduce the effort on coding for different data types
to a single set of code.
Testing and debugging efforts are reduced.
Standard Template Library
In the late 70s Alexander Stepanov first observed that some
algorithms do not depend on some particular
implementation of a data structure but only on a few
fundamental semantic properties of the structure
Developed by Stepanov and Lee at HP labs in 1992
Become part of the C++ Standard in 1994
What’s in STL?
Container classes: vector, list, deque, set, map, and etc

A large collection of algorithms, such as reverse, swap, heap,
and etc.
Vector
A sequence that supports random access to elements
Elements can be inserted and removed at the beginning, the
end and the middle
Constant time random access
Commonly used operations
begin(), end(), size(), [], push_back(
), pop_back(), insert(
),
empty()
Recap
Templates are mechanisms for generating functions
and classes on type parameters. We can design a single
class or function that operates on data of many types
function templates
class templates

Weitere Àhnliche Inhalte

Was ist angesagt?

#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator OverloadingHadziq Fabroyir
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingDustin Chase
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingRai University
 
Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversionsAmogh Kalyanshetti
 
C++ overloading
C++ overloadingC++ overloading
C++ overloadingsanya6900
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading Charndeep Sekhon
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingBurhan Ahmed
 
Operator overloading in C++
Operator  overloading in C++Operator  overloading in C++
Operator overloading in C++BalajiGovindan5
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type ConversionsRokonuzzaman Rony
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKamal Acharya
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++Aabha Tiwari
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloadingMd. Ashraful Islam
 

Was ist angesagt? (20)

#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversions
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading in C++
Operator  overloading in C++Operator  overloading in C++
Operator overloading in C++
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Overloading
OverloadingOverloading
Overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 

Andere mochten auch

Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Templates in c++
Templates in c++Templates in c++
Templates in c++Mayank Bhatt
 
Evangelio Ilutsrado, 4Âș Domingo de Pascua
Evangelio Ilutsrado, 4Âș Domingo de PascuaEvangelio Ilutsrado, 4Âș Domingo de Pascua
Evangelio Ilutsrado, 4Âș Domingo de Pascuacristinamoreubi
 
àč„àž­àč‚àž‹àč€àžĄàž­àžŁàčŒ
àč„àž­àč‚àž‹àč€àžĄàž­àžŁàčŒàč„àž­àč‚àž‹àč€àžĄàž­àžŁàčŒ
àč„àž­àč‚àž‹àč€àžĄàž­àžŁàčŒMaruko Supertinger
 
Palestra Encontro Gamer 2016 - FCS na IndĂșstria de Jogos
Palestra Encontro Gamer 2016 - FCS na IndĂșstria de JogosPalestra Encontro Gamer 2016 - FCS na IndĂșstria de Jogos
Palestra Encontro Gamer 2016 - FCS na IndĂșstria de JogosFabio Lima
 
Revista veja destaca fernando mendes na edição desta semana
Revista veja destaca fernando mendes na edição desta semanaRevista veja destaca fernando mendes na edição desta semana
Revista veja destaca fernando mendes na edição desta semanaEvandro Lira
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Abu Saleh
 
Policy lab user centred insight monday 23rd feb
Policy lab user centred insight monday 23rd febPolicy lab user centred insight monday 23rd feb
Policy lab user centred insight monday 23rd febPolicy Lab
 
Delivering Excellent Support Customer Experiences in Marketing
Delivering Excellent Support Customer Experiences in MarketingDelivering Excellent Support Customer Experiences in Marketing
Delivering Excellent Support Customer Experiences in MarketingDavid Loia
 
Utilizing Social Media to Promote Your Speaking Engagements (ILTA Speakers We...
Utilizing Social Media to Promote Your Speaking Engagements (ILTA Speakers We...Utilizing Social Media to Promote Your Speaking Engagements (ILTA Speakers We...
Utilizing Social Media to Promote Your Speaking Engagements (ILTA Speakers We...InsideLegal
 
final resume
final resumefinal resume
final resumeTejas Pawar
 
Arquitetura de informação
Arquitetura de informaçãoArquitetura de informação
Arquitetura de informaçãoPrinci AgĂȘncia Web
 

Andere mochten auch (20)

Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Templates
TemplatesTemplates
Templates
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Evangelio Ilutsrado, 4Âș Domingo de Pascua
Evangelio Ilutsrado, 4Âș Domingo de PascuaEvangelio Ilutsrado, 4Âș Domingo de Pascua
Evangelio Ilutsrado, 4Âș Domingo de Pascua
 
Mfhp12 c excel_4ed_solucoes
Mfhp12 c excel_4ed_solucoesMfhp12 c excel_4ed_solucoes
Mfhp12 c excel_4ed_solucoes
 
àč„àž­àč‚àž‹àč€àžĄàž­àžŁàčŒ
àč„àž­àč‚àž‹àč€àžĄàž­àžŁàčŒàč„àž­àč‚àž‹àč€àžĄàž­àžŁàčŒ
àč„àž­àč‚àž‹àč€àžĄàž­àžŁàčŒ
 
Palestra Encontro Gamer 2016 - FCS na IndĂșstria de Jogos
Palestra Encontro Gamer 2016 - FCS na IndĂșstria de JogosPalestra Encontro Gamer 2016 - FCS na IndĂșstria de Jogos
Palestra Encontro Gamer 2016 - FCS na IndĂșstria de Jogos
 
Revista veja destaca fernando mendes na edição desta semana
Revista veja destaca fernando mendes na edição desta semanaRevista veja destaca fernando mendes na edição desta semana
Revista veja destaca fernando mendes na edição desta semana
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
Policy lab user centred insight monday 23rd feb
Policy lab user centred insight monday 23rd febPolicy lab user centred insight monday 23rd feb
Policy lab user centred insight monday 23rd feb
 
Delivering Excellent Support Customer Experiences in Marketing
Delivering Excellent Support Customer Experiences in MarketingDelivering Excellent Support Customer Experiences in Marketing
Delivering Excellent Support Customer Experiences in Marketing
 
Utilizing Social Media to Promote Your Speaking Engagements (ILTA Speakers We...
Utilizing Social Media to Promote Your Speaking Engagements (ILTA Speakers We...Utilizing Social Media to Promote Your Speaking Engagements (ILTA Speakers We...
Utilizing Social Media to Promote Your Speaking Engagements (ILTA Speakers We...
 
final resume
final resumefinal resume
final resume
 
Ppt 01
Ppt 01Ppt 01
Ppt 01
 
Resumen
ResumenResumen
Resumen
 
2007 urok greek cafee
2007 urok greek cafee2007 urok greek cafee
2007 urok greek cafee
 
Arquitetura de informação
Arquitetura de informaçãoArquitetura de informação
Arquitetura de informação
 

Ähnlich wie 14 operator overloading

1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
Unit 1
Unit  1Unit  1
Unit 1donny101
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfesuEthopi
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1rehan16091997
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 
chapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfchapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfstudy material
 
Object Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsObject Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsMuhammadTalha436
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++Amresh Raj
 
Functions in C++
Functions in C++Functions in C++
Functions in C++Nikhil Pandit
 
Bc0037
Bc0037Bc0037
Bc0037hayerpa
 

Ähnlich wie 14 operator overloading (20)

C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
C#2
C#2C#2
C#2
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Unit 1
Unit  1Unit  1
Unit 1
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
chapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfchapter-8-function-overloading.pdf
chapter-8-function-overloading.pdf
 
Object Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of ExamsObject Oriented Programming Short Notes for Preperation of Exams
Object Oriented Programming Short Notes for Preperation of Exams
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Bc0037
Bc0037Bc0037
Bc0037
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
02.adt
02.adt02.adt
02.adt
 

Mehr von Docent Education

17 files and streams
17 files and streams17 files and streams
17 files and streamsDocent Education
 
13 exception handling
13 exception handling13 exception handling
13 exception handlingDocent Education
 
12 constructors invocation and data members initialization
12 constructors invocation and data members initialization12 constructors invocation and data members initialization
12 constructors invocation and data members initializationDocent Education
 
12 constructors invocation and data members initialization
12 constructors invocation and data members initialization12 constructors invocation and data members initialization
12 constructors invocation and data members initializationDocent Education
 
11 constructors in derived classes
11 constructors in derived classes11 constructors in derived classes
11 constructors in derived classesDocent Education
 
6 pointers functions
6 pointers functions6 pointers functions
6 pointers functionsDocent Education
 
4 Type conversion functions
4 Type conversion functions4 Type conversion functions
4 Type conversion functionsDocent Education
 
1 Intro Object Oriented Programming
1  Intro Object Oriented Programming1  Intro Object Oriented Programming
1 Intro Object Oriented ProgrammingDocent Education
 
3 intro basic_elements
3 intro basic_elements3 intro basic_elements
3 intro basic_elementsDocent Education
 

Mehr von Docent Education (15)

17 files and streams
17 files and streams17 files and streams
17 files and streams
 
16 virtual function
16 virtual function16 virtual function
16 virtual function
 
13 exception handling
13 exception handling13 exception handling
13 exception handling
 
12 constructors invocation and data members initialization
12 constructors invocation and data members initialization12 constructors invocation and data members initialization
12 constructors invocation and data members initialization
 
12 constructors invocation and data members initialization
12 constructors invocation and data members initialization12 constructors invocation and data members initialization
12 constructors invocation and data members initialization
 
11 constructors in derived classes
11 constructors in derived classes11 constructors in derived classes
11 constructors in derived classes
 
10 inheritance
10 inheritance10 inheritance
10 inheritance
 
7 class objects
7 class objects7 class objects
7 class objects
 
6 pointers functions
6 pointers functions6 pointers functions
6 pointers functions
 
5 array
5 array5 array
5 array
 
4 Type conversion functions
4 Type conversion functions4 Type conversion functions
4 Type conversion functions
 
1 Intro Object Oriented Programming
1  Intro Object Oriented Programming1  Intro Object Oriented Programming
1 Intro Object Oriented Programming
 
3 intro basic_elements
3 intro basic_elements3 intro basic_elements
3 intro basic_elements
 
2 Intro c++
2 Intro c++2 Intro c++
2 Intro c++
 
unit-1-intro
 unit-1-intro unit-1-intro
unit-1-intro
 

KĂŒrzlich hochgeladen

MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLSeo
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Delhi Call girls
 
Grateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfGrateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfPaul Menig
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayNZSG
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsP&CO
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyEthan lee
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.Aaiza Hassan
 
Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...Roland Driesen
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMRavindra Nath Shukla
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...Aggregage
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...anilsa9823
 
RSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataRSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataExhibitors Data
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Trucks in Minnesota
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Dave Litwiller
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMANIlamathiKannappan
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdfRenandantas16
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756dollysharma2066
 

KĂŒrzlich hochgeladen (20)

Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pillsMifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
 
Grateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfGrateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdf
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 May
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and pains
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
 
M.C Lodges -- Guest House in Jhang.
M.C Lodges --  Guest House in Jhang.M.C Lodges --  Guest House in Jhang.
M.C Lodges -- Guest House in Jhang.
 
Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...Boost the utilization of your HCL environment by reevaluating use cases and f...
Boost the utilization of your HCL environment by reevaluating use cases and f...
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSM
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
 
RSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors DataRSA Conference Exhibitor List 2024 - Exhibitors Data
RSA Conference Exhibitor List 2024 - Exhibitors Data
 
VVVIP Call Girls In Greater Kailash âžĄïž Delhi âžĄïž 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash âžĄïž Delhi âžĄïž 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Greater Kailash âžĄïž Delhi âžĄïž 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash âžĄïž Delhi âžĄïž 9999965857 🚀 No Advance 24HRS...
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through Cartoons
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMAN
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
 

14 operator overloading

  • 1. UNIT III Overloading 09/04/131 VIT - SCSE By G.SasiKumar., M.E., (Ph.D)., Assistant Professor School of Computing Science and Engineering VIT University
  • 2. Functions in C++ Experience has shown that the best way to develop and maintain large programs is to construct it from smaller pieces (Modules) This technique Called “Divide and Conquer” ‱Easer To Design Build Debug Extend Modify Understand Reuse Better Organization Wise Development Approach main() { ----- ---- } function f1() { --- --- } function f2() { --- --- }
  • 3. Function Overloading C++ supports writing more than one function with the same name but different argument lists. This could include: different data types different number of arguments The advantage is that the same apparent function can be called to perform similar but different tasks. The following will show an example of this.
  • 4. Function Overloading void swap (int *a, int *b) ; void swap (float *c, float *d) ; void swap (char *p, char *q) ; int main ( ) { int a = 4, b = 6 ; float c = 16.7, d = -7.89 ; char p = 'M' , q = 'n' ; swap (&a, &b) ; swap (&c, &d) ; swap (&p, &q) ; } void swap (int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } void swap (float *c, float *d) { float temp; temp = *c; *c = *d; *d = temp; } void swap (char *p, char *q) { char temp; temp = *p; *p = *q; *q = temp; }
  • 5. 09/04/135 VIT - SCSE ‱ Operator Overloading refers to giving the normal C++ Operators, such as +,*,<= etc., additional meanings when they are applied to user defined data types. ‱ Simply defined as to create new definitions for operators. Syntax : <ret.datatype> operator <operator name>() { --- --- } Operator Overloading
  • 6. The steps involved an operator are : 1. Create a class that defines a data type that is to be used in the overloading operation 2. Declare the operator function as either a member function or a friend function inside the class 3. Define the operator function either inside or outside the class 4. Use the operator in the main() function
  • 7. ‱ All the operators can be overloaded using friend function except () [] -> and =. These operators must be defined by using a member function. ASSIGNMENT OPERATOR OVERLOADING RULES : ‱ The operator function for the assignment operator are inherited by any derived class. ‱ Friend functions cannot be used to overload the assignment operator
  • 8. The operators that can be overloaded are + - * / % ^ & | _ != < > <= >= += -+ *= != ++ -- [ ] () || &= && -> , new delete The operators that cannot be overloaded are # .(member operator) :: sizeof ?:
  • 9. 09/04/139 VIT - SCSE class sample { private: int x; float y; public: sample(int,float); void operator =(sample s); void display(); }; sample::sample(int one,float two) { x=one; y=two; } void sample::operator =(sample s) { x=s.x; y=s.y; } void sample::display() { cout<<”integer number(x)=:”<<x<<endl; cout<<”floating value(y)=:”<<y<<endl; cout<<endl; } (Unary)Overloading Assignment Operator (=)
  • 10. 09/04/1310 VIT - SCSE void main() { sample ob1(10,4.5); sample ob2(20,6.2); ob1=ob2; cout<<”contents of the first object n”; ob1.display(); cout<<”contents of the second object n”; ob2.display(); }
  • 11. 09/04/1311 VIT - SCSE class sample { private : int x; public : sample() { x=0; } int getcount() { return x; } sample operator ++() { ++x; sample t; t.x=x; return t; }}; void main() { sample s1,s2; cout<<"s1 ="<<s1.getcount()<<endl; cout<<"s2 ="<<s2.getcount()<<endl; ++s1; s2=++s1; cout<<"s1 ="<<s1.getcount()<<endl; cout<<"s2 ="<<s2.getcount()<<endl; getch(); } Overloading ++ Operator OUTPUT : s1 = 0 s2 = 0 s1 = 2 s2 = 2
  • 12. 09/04/1312 VIT - SCSE class sample { private: int x; public: sample(); sample(int); sample operator +(sample s); void display(); }; sample::sample() { x=0; } sample::sample(int one) { x=one; } sample sample::operator + (sample s) { sample t; t.x=x+s.x; return(t); } void sample::display() { cout<<”X=”<<x<<endl; } (Binary) Overloading Arithmetic Operators (+)
  • 13. 09/04/1313 VIT - SCSE void main() { sample ob1(10); sample ob2(20); sample ob3; ob3=ob1+ob2; ob1.display(); ob2.display(); ob3.display(); } OUTPUT : X=10 X=20 X=30
  • 14. 09/04/1314 VIT - SCSE class sample { private: int x; public: sample(); sample(int); sample operator -(sample s); void display(); }; sample::sample() { x=0; } sample::sample(int one) { x=one; } sample sample::operator - (sample s) { sample t; t.x=x-s.x; return(t); } void sample::display() { cout<<”X=”<<x<<endl; } (Binary) Overloading Arithmetic Operators (-)
  • 15. 09/04/1315 VIT - SCSE void main() { sample ob1(10); sample ob2(20); sample ob3; ob3=ob1-ob2; ob1.display(); ob2.display(); ob3.display(); } OUTPUT : X=10 X=20 X=-10
  • 16. #include<iostream.h> const int SIZE=5; class test { private : int a[SIZE]; public: int operator [] (int i) { return i; } }; void main() { test t1; int i; OVERLOADING THE SUBSRIPTOPERATOR [ ] for(i=1;i<=SIZE;i++) { // control is transferred to the operator function call int operator [] (int i) cout<<t1[i]<<"t";} } OUTPUT : 1 2 3 4 5
  • 17. 09/04/1317 VIT - SCSE class sample { private: int x; public: sample(); sample(int one); void display(); int operator <(sample s); }; sample::sample() { x=0; } sample::sample(int one) { x=one; } void sample::display() { cout<<"X="<<x<<endl; } int sample::operator <(sample s) { return (x<s.x); } void main() { sample ob1(20); sample ob2(100); cout<<(ob1<ob2)<<endl; cout<<(ob2<ob1)<<endl; getch(); } Overloading Arithmetic Comparison Operators (<) OUTPUT : 1 0
  • 18. 09/04/1318 VIT - SCSE class sample { private: int x; public: sample(); sample(int); sample operator +=(sample s); void display(); }; sample::sample() { x=0; } sample::sample(int one) { x=one; } sample sample::operator +=(sample s) { return(x+=s.x); } void sample::display() { cout<<"X="<<x<<endl; } void main() { sample ob1(10); sample ob2(20); ob1.display(); ob2.display(); ob2+=ob1; ob1.display(); ob2.display(); } Overloading Compound Assignment Operator (+=) OUTPUT : X=10 X=20 X=10 X=30
  • 19. 09/04/1319 VIT - SCSE class sample { private: int x; public: sample(); sample(int one); void display(); int operator <=(sample s); }; sample::sample() { x=0; } sample::sample(int one) { x=one; } void sample::display() { cout<<"X="<<x<<endl; } int sample::operator <=(sample s) { return (x<=s.x); } void main() { sample ob1(20); sample ob2(100); cout<<(ob1<=ob2)<<endl; cout<<(ob2<=ob1)<<endl; getch(); } Overloading Compound Assignment Operator (<=) OUTPUT : 1 0
  • 20. Increment and Decrement Operators We have used n++; and ++n; to replace for n = n + 1; and we have used --n and n--; to replace for n = n - 1; The expressions n++ and ++n have values. The expression n++ returns the value of n before to incrementing, then increments the value of n. ++n increments the value of n, then returns the incremented value. The expressions n-- and --n have values as well. The expression n-- returns the value of n before to decrementing, then decrements the value of n. --n decrements the value of n, then returns the decremented value.
  • 21. Overloading ++ and - - With C++, you use ++ to increment variables, and - - to decrement variables When a prefix operator such as ++ is used in an expression, the mathematical operation takes place before the expression is evaluated When the postfix operator is used, the expression is evaluated before the mathematical operation takes place
  • 22. Using the Prefix and Postfix ++ Operators with an Integer
  • 23. Generic Programming for Templates A methodology for the development of reusable software libraries Three primary tasks: Categorize the abstractions in a domain into concepts Implement generic algorithms based on the concepts Build concrete models of the concepts Concepts make templates easier to use Express requirements directly in code Provide complete type-checking of templates
  • 24. Characteristics of Generic Libraries Reusable: able to operate on user-defined data types Composable: able to operate on data types defined in another library Efficient: performance on par with non-generic, hand- coded implementations
  • 25. C++ Templates  C++ Function Templates -- C++ Function templates are those functions which can handle different data types without separate code for each of them.   C++ Class Templates -- C++ Class Templates are used where we have multiple copies of code for different data types with the same logic.
  • 26. Templates Constructs a family of related functions or class Different Approach – Function    Example 1 & 2 : int Add(int a,int b) { return a+b;} // function Without C++ template float Add(float a, float b) { return a+b;} // function Without C++ template 1. NaĂŻve Approach Different Function Definitions Different Function Names 2. Function Overloading Different Function Definitions Same Function Name 3. Template Functions One Function Definition (a function template) Compiler Generates Individual Functions
  • 27. Approach 3: Function Template ‱ A C++ language construct that allows the compiler to generate multiple versions of a function by allowing parameterized data types. Template < TemplateParamList > FunctionDefinition FunctionTemplate TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier
  • 28. Example of a Function Template template<class T> T Add(T a,T b)//C++ Fucntion Template sample { return a+b; } Template parameter (class, user defined type, built-in types)
  • 29. Class Template ‱ A C++ language construct that allows the compiler to generate multiple versions of a class by allowing parameterized data types. Template < TemplateParamList > ClassDefinition Class Template TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier
  • 30. Example of a Class Template template<class ItemType> class GList { public: bool IsEmpty() const; bool IsFull() const; int Length() const; void Insert( /* in */ ItemType item ); void Delete( /* in */ ItemType item ); bool IsPresent( /* in */ ItemType item ) const; void SelSort(); void Print() const; GList(); // Constructor private: int length; ItemType data[MAX_LENGTH]; }; Template parameter
  • 31. Advantages of C++ Class Templates:  One C++ Class Template can handle different types of parameters. Compiler generates classes for only the used types. If the template is instantiated for int type, compiler generates only an int version for the c++ template class. Templates reduce the effort on coding for different data types to a single set of code. Testing and debugging efforts are reduced.
  • 32. Standard Template Library In the late 70s Alexander Stepanov first observed that some algorithms do not depend on some particular implementation of a data structure but only on a few fundamental semantic properties of the structure Developed by Stepanov and Lee at HP labs in 1992 Become part of the C++ Standard in 1994
  • 33. What’s in STL? Container classes: vector, list, deque, set, map, and etc
 A large collection of algorithms, such as reverse, swap, heap, and etc. Vector A sequence that supports random access to elements Elements can be inserted and removed at the beginning, the end and the middle Constant time random access Commonly used operations begin(), end(), size(), [], push_back(
), pop_back(), insert(
), empty()
  • 34. Recap Templates are mechanisms for generating functions and classes on type parameters. We can design a single class or function that operates on data of many types function templates class templates