SlideShare une entreprise Scribd logo
1  sur  32
BIRLA INSTITUTE OF TECHNOLOGY
MESRA-RANCHI
JAIPUR CAMPUS
TOPIC:-
POLYMORPHISM AND TEMPLATES
SUBMITTED BY:
YASH SOGANI MCA/25025/18
ANUSHKA PAREEK MCA/25024/18
OVERVIEW
 POLYMORPHISM
• COMPILE TIME POLYMORPHISM
• RUNTIME POLYMORPHISM
 VIRTUAL FUNCTIONS
 ABSTRACT CLASSES
POLYMORPHISM
The word polymorphism means having many forms. In
simple words, we can define polymorphism as the ability
of a message to be displayed in more than one form.
In C++ polymorphism is mainly divided into two types:
1.Compile time Polymorphism
2.Runtime Polymorphism
COMPILE TIME POLYMORPHISM
This type of polymorphism is achieved by using
the 2 following ways:
1.Function overloading
2.Operator overloading
FUNCTION OVERLOADING
When there are multiple functions with same name
but different parameters then these functions are said
to be overloaded. Functions can be overloaded
by change in number of arguments or/and change in
type of arguments.
// C++ program for function overloading
#include <iostream.h>
class Geeks
{
public:
// function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
// function with same name but 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}
// function with same name and 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};
int main() {
Geeks obj1;
// Which function is called will depend on the parameters passed
// The first 'func' is called
obj1.func(7);
// The second 'func' is called
obj1.func(9.132);
// The third 'func' is called
obj1.func(85,64);
return 0;
}
OUTPUT:-
value of x is 7
value of x is 9.132
value of x and y is 85,64
OPERATOR OVERLOADING
C++ also provide option to overload operators. For example,
we can make the operator (‘+’) for string class to concatenate
two strings. We know that this is the addition operator whose
task is to add to operands. So a single operator ‘+’ when
placed between integer operands , adds them and when
placed between string operands it concatenates them.
RUNTIME POLYMORPHISM
This type of polymorphism is achieved by Function
Overriding.
FUNCTION OVERRIDING
It occurs when a derived class has a definition for one
of the member functions of the base class. That base
function is said to be overridden.
VIRTUAL FUNCTION
A virtual function is a function in a base class that is declared
using the keyword virtual. Defining in a base class a virtual
function, with another version in a derived class, signals to the
compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at
any given point in the program to be based on the kind of
object for which it is called. This sort of operation is referred to
as dynamic linkage, or late binding.
// C++ program for function overriding
#include<iostream.h>
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print () //print () is already virtual function in derived class,
we could also declared as virtual void print () explicitly
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};
//main function
int main()
{
base *bptr;
derived d;
bptr = &d;
//virtual function, binded at runtime (Runtime polymorphism)
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
OUTPUT:-
print derived class
show base class
ABSTRACT CLASSES
An abstract class is a class that is designed to be specifically
used as a base class. It contains at least one Pure Virtual
function in it. Abstract classes are used to provide an Interface
for its sub classes. Classes inheriting an Abstract Class must
provide definition to the pure virtual function, otherwise they
will also become abstract class.
#include<iostream.h>
class Base
{
public:
virtual void fun() = 0;
};
// This class inherits from Base and implements fun()
class Derived: public Base
{
public:
void fun()
{
cout << “fun() called";
}
};
int main(void)
{
Derived d;
d.fun();
return 0;
}
OUTPUT:-
func() called
Templates
PRESENTED BY :
ANUSHKA PAREEK
MCA/25024/18
Templates?
 Templates are a feature of the C++
programming language that allow
functions and classes to operate with
generic types.
 This allows a function or class to work on
many different data types without being
rewritten for each one.
Types of Templates
C++ provides two types of templates :
 Class Templates
 Function Templates
Function Template
 Function templates are special functions that can operate with generic
types. This allows us to create a function template whose functionality can
be adapted to more than one type or class without repeating the entire
code for each type.
 These define the logic behind the algorithms that work for multiple data
types.
 In C++ , this can be achieved using template parameters.
Template Parameter & Syntax
 A template parameter is a special kind of parameter that can
be used to pass a type as argument: just like regular
function parameters can be used to pass values to function,
template parameter allow to pass values and types to a
function.
template < T0, T1… Tn>
Keyword Parameters
template <class T>
T min (T var1, T var2); // Returns a value of type T
Ex : Finding the max of two number
int maximum(int a, int b)
{
if (a > b)
return a;
else
return b;
}
int maximum(double a,
double b)
{
if (a > b)
return a;
else
return b;
}
Function with integer data type Function with double data type
C++ routines work on specific types. We often need to
write different routines to perform the same operation
on different data types.
Template Function
template <class Item>
Item maximum(Item a,
Item b)
{
if (a > b)
return a;
else
return b;
}
Function templates allow the logic to be
written once and used for all data types –
generic function.
It uses Item as its data type.
This function can now be used with any
data type depending on the value of a
& b passed.
#include <iostream.h>
using namespace std;
// One function works for all data types.
template <typename T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
cout << myMax<char>('g', 'e') << endl; // call myMax for char
return 0;
}
CLASS TEMPLATES
 These define generic class patterns into which specific data
types can be plugged in to produce new classes.
 Class templates encourage software reusability by enabling
type-specific versions of generic classes to be instantiated.
Syntax
template <class T>
class className
{
... .. ...
public: T var;
T someOperation(T arg);
... .. ...
};
//Creating class template object
className<dataType> classObject;
#include <iostream>
using namespace std;
template <class T>
class Calculator //Calculator Program
{
private: T num1, num2;
public: Calculator(T n1, T n2)
{ num1 = n1; num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
T subtract()
{
return num1 - num2;
}
T multiply()
{
return num1 * num2;
}
T divide()
{
return num1 / num2;
}
};
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
cout << "Int results:" << endl;
intCalc.displayResult();
cout << endl << "Float results:" << endl;
floatCalc.displayResult();
return 0;
}
Thank you

Contenu connexe

Tendances

Tendances (20)

Operator Overloading and Scope of Variable
Operator Overloading and Scope of VariableOperator Overloading and Scope of Variable
Operator Overloading and Scope of Variable
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
Generics
GenericsGenerics
Generics
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA Polymorphism
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)
 
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
Polymorphism in c++ ppt (Powerpoint) | Polymorphism in c++ with example ppt |...
 
Oo Design And Patterns
Oo Design And PatternsOo Design And Patterns
Oo Design And Patterns
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function different types of funtion
Function different types of funtionFunction different types of funtion
Function different types of funtion
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 

Similaire à Polymorphism & Templates

Chapter 13.1.6
Chapter 13.1.6Chapter 13.1.6
Chapter 13.1.6
patcha535
 
Comparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismComparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphism
CHAITALIUKE1
 

Similaire à Polymorphism & Templates (20)

Chapter 13.1.6
Chapter 13.1.6Chapter 13.1.6
Chapter 13.1.6
 
C++ concept of Polymorphism
C++ concept of  PolymorphismC++ concept of  Polymorphism
C++ concept of Polymorphism
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdf
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Comparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismComparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphism
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptx
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptx
 
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
C++ first s lide
C++ first s lideC++ first s lide
C++ first s lide
 
oops.pptx
oops.pptxoops.pptx
oops.pptx
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
C questions
C questionsC questions
C questions
 
CJPCCS BCA VISNAGAR functions in C language
CJPCCS BCA VISNAGAR  functions in C languageCJPCCS BCA VISNAGAR  functions in C language
CJPCCS BCA VISNAGAR functions in C language
 

Plus de Meghaj Mallick

Plus de Meghaj Mallick (20)

24 partial-orderings
24 partial-orderings24 partial-orderings
24 partial-orderings
 
PORTFOLIO BY USING HTML & CSS
PORTFOLIO BY USING HTML & CSSPORTFOLIO BY USING HTML & CSS
PORTFOLIO BY USING HTML & CSS
 
Introduction to Software Testing
Introduction to Software TestingIntroduction to Software Testing
Introduction to Software Testing
 
Introduction to System Programming
Introduction to System ProgrammingIntroduction to System Programming
Introduction to System Programming
 
MACRO ASSEBLER
MACRO ASSEBLERMACRO ASSEBLER
MACRO ASSEBLER
 
Icons, Image & Multimedia
Icons, Image & MultimediaIcons, Image & Multimedia
Icons, Image & Multimedia
 
Project Tracking & SPC
Project Tracking & SPCProject Tracking & SPC
Project Tracking & SPC
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
 
Routing in MANET
Routing in MANETRouting in MANET
Routing in MANET
 
Macro assembler
 Macro assembler Macro assembler
Macro assembler
 
Architecture and security in Vanet PPT
Architecture and security in Vanet PPTArchitecture and security in Vanet PPT
Architecture and security in Vanet PPT
 
Design Model & User Interface Design in Software Engineering
Design Model & User Interface Design in Software EngineeringDesign Model & User Interface Design in Software Engineering
Design Model & User Interface Design in Software Engineering
 
Text Mining of Twitter in Data Mining
Text Mining of Twitter in Data MiningText Mining of Twitter in Data Mining
Text Mining of Twitter in Data Mining
 
DFS & BFS in Computer Algorithm
DFS & BFS in Computer AlgorithmDFS & BFS in Computer Algorithm
DFS & BFS in Computer Algorithm
 
Software Development Method
Software Development MethodSoftware Development Method
Software Development Method
 
Secant method in Numerical & Statistical Method
Secant method in Numerical & Statistical MethodSecant method in Numerical & Statistical Method
Secant method in Numerical & Statistical Method
 
Motivation in Organization
Motivation in OrganizationMotivation in Organization
Motivation in Organization
 
Communication Skill
Communication SkillCommunication Skill
Communication Skill
 
Partial-Orderings in Discrete Mathematics
 Partial-Orderings in Discrete Mathematics Partial-Orderings in Discrete Mathematics
Partial-Orderings in Discrete Mathematics
 
Hashing In Data Structure
Hashing In Data Structure Hashing In Data Structure
Hashing In Data Structure
 

Dernier

If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
Kayode Fayemi
 
Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
Kayode Fayemi
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
raffaeleoman
 
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
Sheetaleventcompany
 

Dernier (20)

Dreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio IIIDreaming Music Video Treatment _ Project & Portfolio III
Dreaming Music Video Treatment _ Project & Portfolio III
 
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
 
Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)
 
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docxANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
 
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptxMohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptx
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
 
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, YardstickSaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
 
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfThe workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
 
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyCall Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
 
lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.lONG QUESTION ANSWER PAKISTAN STUDIES10.
lONG QUESTION ANSWER PAKISTAN STUDIES10.
 
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
 
Uncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac FolorunsoUncommon Grace The Autobiography of Isaac Folorunso
Uncommon Grace The Autobiography of Isaac Folorunso
 
Dreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video TreatmentDreaming Marissa Sánchez Music Video Treatment
Dreaming Marissa Sánchez Music Video Treatment
 
Presentation on Engagement in Book Clubs
Presentation on Engagement in Book ClubsPresentation on Engagement in Book Clubs
Presentation on Engagement in Book Clubs
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
 
ICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdfICT role in 21st century education and it's challenges.pdf
ICT role in 21st century education and it's challenges.pdf
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510
 
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdfAWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
AWS Data Engineer Associate (DEA-C01) Exam Dumps 2024.pdf
 
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
No Advance 8868886958 Chandigarh Call Girls , Indian Call Girls For Full Nigh...
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar Training
 

Polymorphism & Templates

  • 1. BIRLA INSTITUTE OF TECHNOLOGY MESRA-RANCHI JAIPUR CAMPUS TOPIC:- POLYMORPHISM AND TEMPLATES SUBMITTED BY: YASH SOGANI MCA/25025/18 ANUSHKA PAREEK MCA/25024/18
  • 2. OVERVIEW  POLYMORPHISM • COMPILE TIME POLYMORPHISM • RUNTIME POLYMORPHISM  VIRTUAL FUNCTIONS  ABSTRACT CLASSES
  • 3. POLYMORPHISM The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. In C++ polymorphism is mainly divided into two types: 1.Compile time Polymorphism 2.Runtime Polymorphism
  • 4. COMPILE TIME POLYMORPHISM This type of polymorphism is achieved by using the 2 following ways: 1.Function overloading 2.Operator overloading
  • 5. FUNCTION OVERLOADING When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.
  • 6. // C++ program for function overloading #include <iostream.h> class Geeks { public: // function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } // function with same name but 1 double parameter void func(double x) { cout << "value of x is " << x << endl; }
  • 7. // function with same name and 2 int parameters void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } }; int main() { Geeks obj1; // Which function is called will depend on the parameters passed // The first 'func' is called obj1.func(7); // The second 'func' is called obj1.func(9.132); // The third 'func' is called obj1.func(85,64); return 0; }
  • 8. OUTPUT:- value of x is 7 value of x is 9.132 value of x and y is 85,64
  • 9. OPERATOR OVERLOADING C++ also provide option to overload operators. For example, we can make the operator (‘+’) for string class to concatenate two strings. We know that this is the addition operator whose task is to add to operands. So a single operator ‘+’ when placed between integer operands , adds them and when placed between string operands it concatenates them.
  • 10. RUNTIME POLYMORPHISM This type of polymorphism is achieved by Function Overriding. FUNCTION OVERRIDING It occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
  • 11. VIRTUAL FUNCTION A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function. What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding.
  • 12. // C++ program for function overriding #include<iostream.h> class base { public: virtual void print () { cout<< "print base class" <<endl; } void show () { cout<< "show base class" <<endl; } };
  • 13. class derived:public base { public: void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly { cout<< "print derived class" <<endl; } void show () { cout<< "show derived class" <<endl; } };
  • 14. //main function int main() { base *bptr; derived d; bptr = &d; //virtual function, binded at runtime (Runtime polymorphism) bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0; }
  • 16. ABSTRACT CLASSES An abstract class is a class that is designed to be specifically used as a base class. It contains at least one Pure Virtual function in it. Abstract classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide definition to the pure virtual function, otherwise they will also become abstract class.
  • 17. #include<iostream.h> class Base { public: virtual void fun() = 0; }; // This class inherits from Base and implements fun() class Derived: public Base { public: void fun() { cout << “fun() called"; } };
  • 18. int main(void) { Derived d; d.fun(); return 0; } OUTPUT:- func() called
  • 19. Templates PRESENTED BY : ANUSHKA PAREEK MCA/25024/18
  • 20. Templates?  Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types.  This allows a function or class to work on many different data types without being rewritten for each one.
  • 21. Types of Templates C++ provides two types of templates :  Class Templates  Function Templates
  • 22. Function Template  Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.  These define the logic behind the algorithms that work for multiple data types.  In C++ , this can be achieved using template parameters.
  • 23. Template Parameter & Syntax  A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to function, template parameter allow to pass values and types to a function. template < T0, T1… Tn> Keyword Parameters template <class T> T min (T var1, T var2); // Returns a value of type T
  • 24. Ex : Finding the max of two number int maximum(int a, int b) { if (a > b) return a; else return b; } int maximum(double a, double b) { if (a > b) return a; else return b; } Function with integer data type Function with double data type C++ routines work on specific types. We often need to write different routines to perform the same operation on different data types.
  • 25. Template Function template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } Function templates allow the logic to be written once and used for all data types – generic function. It uses Item as its data type. This function can now be used with any data type depending on the value of a & b passed.
  • 26. #include <iostream.h> using namespace std; // One function works for all data types. template <typename T> T myMax(T x, T y) { return (x > y)? x: y; } int main() { cout << myMax<int>(3, 7) << endl; // Call myMax for int cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double cout << myMax<char>('g', 'e') << endl; // call myMax for char return 0; }
  • 27. CLASS TEMPLATES  These define generic class patterns into which specific data types can be plugged in to produce new classes.  Class templates encourage software reusability by enabling type-specific versions of generic classes to be instantiated.
  • 28. Syntax template <class T> class className { ... .. ... public: T var; T someOperation(T arg); ... .. ... }; //Creating class template object className<dataType> classObject;
  • 29. #include <iostream> using namespace std; template <class T> class Calculator //Calculator Program { private: T num1, num2; public: Calculator(T n1, T n2) { num1 = n1; num2 = n2; } void displayResult() { cout << "Numbers are: " << num1 << " and " << num2 << "." << endl; cout << "Addition is: " << add() << endl; cout << "Subtraction is: " << subtract() << endl; cout << "Product is: " << multiply() << endl; cout << "Division is: " << divide() << endl; }
  • 30. T subtract() { return num1 - num2; } T multiply() { return num1 * num2; } T divide() { return num1 / num2; } };
  • 31. int main() { Calculator<int> intCalc(2, 1); Calculator<float> floatCalc(2.4, 1.2); cout << "Int results:" << endl; intCalc.displayResult(); cout << endl << "Float results:" << endl; floatCalc.displayResult(); return 0; }