Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Functions in C++
Lecture Slides By Adil Aslam
My Email Address:
adilaslam5959@gmail.com
Object Oriented Programming in C++...
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
About Me
i am Student of BSCS
My email address:
adilaslam5...
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Function in C++
Function in C++
• A function is a group of statements that together
perform a specific task. Every C++ program has at
leas...
Function in C++
• Advantage of Function
• Creating functions in a program is beneficial. They
• Avoid repetition of codes....
Type of Function
• There are two type of function in C++ Language.
They are;
• Library function or pre-define function.
• ...
Library function
• Library functions are those which are predefined in C++
compiler. The implementation part of pre-define...
User Defined Function
• These functions are created by programmer
according to their requirement for example
suppose you w...
Components of Function
• A function usually has three components.
• They are:
• Function prototype/declaration
• Function ...
1-Function Prototype/Declaration
• Function declaration informs the compiler about the
function's name, type and number of...
2-Function definition
Defining of function is nothing but give body of
function that means write logic inside function bod...
Return type: A function may return a value. The return_type
is the data type of the value the function returns.Return type...
Return Statement
• Function can return values. A return statement is used to
return values to the invoking function. The t...
3-Function call
• Function call statement calls the function by matching its
name and arguments. A function call can be ma...
Example of Function
void sum(); // declaring a function
a=10,b=20, c;
void sum() // defining function
{
c=a+b;
cout<<"Sum:...
Functions in C++
• There are two approaches to passing argument to
a function:
• Call by Value
• Call by Reference/Address...
Call by value
• When a function is called, the called function
creates a copy of all the arguments present in the
calling ...
Call by value
• In call by value mechanism, the called function
creates a new set of variables in stack and copies
the val...
Example of call by value-1
void swap(int x, int y)
{
int z;
z = x;
x = y;
y = z;
cout<<"Swapped value a is: = "<<x<<endl;
...
Example of call by value-2
int main ()
{
int a = 7, b = 4;
cout<<"Original values a is: "<<a<<endl;
cout<<"Original values...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
No change the original...
Call By Reference
• In call by reference mechanism, instead of passing
values to the function being called, references/poi...
Example of call by Reference-1
void swap(int *x, int *y)
{
int z;
z = *x;
*x = *y;
*y = z;
cout<<"Swapped value a is: = "<...
Example of call by Reference-2
int main ()
{
int a = 7, b = 4;
cout<<"Original values a is: "<<a<<endl;
cout<<"Original va...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
The original values ar...
Value Vs. Pass By Reference
• Pass by value:
• Makes copy of actual parameter
• Passes copy of contents
• Original variabl...
Function Overloading in C++
• Whenever same method name is exiting multiple times in
the same class with different number ...
Function Overloading in C++
• What is overloading
• Doing work in different way is called overloading.
• What is function ...
Function Overloading (Syntax)
class class_Name {
Returntype method()
{
...........
...........
}
Returntype method(datatyp...
Function Overloading in C++
• These functions having different number or type (or both)
of parameters are known as overloa...
Function Overloading in C++
• The number and type of arguments passed to these
two functions are same even though the retu...
Function Overloading in C++
• Different ways to overload the method
• There are two ways to overload the method in C++:
• ...
By Changing Number of Arguments
class Addition {
public:
void sum(int a, int b) {
cout<<a+b;
}
void sum(int a, int b, int ...
By Changing Number of Arguments
class Addition {
public:
void sum(int a, int b) {
cout<<a+b;
}
void sum(int a, int b, int ...
By Changing Number of Arguments
class Addition {
public:
void sum(int a, int b) {
cout<<a+b;
}
void sum(int a, int b, int ...
By Changing Number of Arguments
class Addition {
public:
void sum(int a, int b) {
cout<<a+b;
}
void sum(int a, int b, int ...
By Changing Number of Arguments
class Addition {
public:
void sum(int a, int b) {
cout<<a+b;
}
void sum(int a, int b, int ...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
By Changing the Data Type
class Addition {
public:
void sum(int a, int b) {
cout<<a+b;
}
void sum(float a, float b) {
cout...
By Changing the Data Type
class Addition {
public:
void sum(int a, int b) {
cout<<a+b;
}
void sum(float a, float b) {
cout...
By Changing the Data Type
class Addition {
public:
void sum(int a, int b) {
cout<<a+b;
}
void sum(float a, float b) {
cout...
By Changing the Data Type
class Addition {
public:
void sum(int a, int b) {
cout<<a+b;
}
void sum(float a, float b) {
cout...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
int absolute(int);
float absolute(float);
int main() {
int a = -5; float b = 5.5;
cout << "Absolute value of " << a << " =...
Explanation of Previous Program
• In the previous example, two functions absolute() are
overloaded.
• Both functions take ...
Function Overloading in C++
Note: The scope of overloading is within the class.
• Can we overload constructor in C++
• Yes...
Your Task… ..1
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f...
Your Task… ..2
int main() {
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.pri...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Default Arguments
• When we mention a default value for a parameter while
declaring the function, it is said to be as defa...
Default Arguments
void sum(int x,int y=0,int z=0)
{
cout << x+y+z<<endl;
}
int main()
{
sum(10);
sum(10,0);
sum(10,20);
su...
Default Arguments
void sum(int x,int y=0,int z=0)
{
cout << x+y+z<<endl;
}
int main()
{
sum(10);
sum(10,0);
sum(10,20);
su...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
One Example of default argument value
int Add(int x, int y=20, int z=30) {
return x + y + z;
}
int main() {
int rs;
rs = A...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Rules for using Default Arguments
• Only the last argument must be given default value. You
cannot have a default argument...
Placeholder Arguments
• When arguments in a function are declared without
any identifier they are called placeholder
argum...
Inline Function in C++
• Inline Function is powerful concept in C++ programming
language. If a function is inline, the com...
Inline Function in C++
• An inline function is a combination of macro &
function. At the time of declaration or definition...
Inline Function in C++
• Inline functions provide following advantages:
• Function call overhead doesn’t occur.
• It speed...
Inline Function in C++
• Compiler may not perform inlining in such
circumstances like:
• If a function contains a loop. (f...
Inline Function in C++
• Some important points to be noted
• Function is made inline by putting a word inline in the
begin...
Inline Function in C++
• When to use Inline functions
• Function can be made as inline as per programmer
need. Some useful...
Inline Function in C++
• Syntax
• Example
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
inline data_type...
Example of Inline Function
inline void show()
{
cout<<"Hello World";
}
int main()
{
show(); // Call it like a normal funct...
Example of Inline Function
inline void show()
{
cout<<"Hello World";
}
int main()
{
show(); // Call it like a normal funct...
Another Example of inline Function
inline int Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the progra...
Another Example of inline Function
inline int Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the progra...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Inline Functions
• Limitations of Inline Functions
• Large Inline functions cause Cache misses and affect
performance nega...
Nested Member Function of a Class
• We just discussed that a function of a class can be
called only by an object of that c...
Nested Member Function Example-1
class comparing {
int m , n;
public:
void input(void);
void display(void);
int larger(voi...
Nested Member Function Example-2
int comparing :: larger(void)
{
if (m >= n) {
return (m);
}
else {
return (n);
}
}
int ma...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Static Member Functions
• These functions work for the class as whole rather
than for a particular object of a class.
• It...
Static Member Functions Example
class A
{
public:
static void f()
{
cout<<"n My Name is Adil Aslam";
}
};
int main()
{
A::...
Static Member Functions Example
class A
{
public:
static void f()
{
cout<<"n My Name is Adil Aslam";
}
};
int main()
{
A::...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Static Member Functions Example
class A
{
public:
void f()
{
cout<<"n My Name is Adil Aslam";
}
};
int main()
{
A::f();
}
...
Compiler View
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Compiler View
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
These functions cannot access
ordinary data ...
Another Example of Static Member Functions-1
class Box {
public:
static int objectCount; //Static Data Member
// Construct...
Another Example of Static Member Functions-2
private:
double length; // Length of a box
double breadth; // Breadth of a bo...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Predict the Output of Following C++ Program
class A {
public:
A() { cout << "A's Constructor Called " << endl; }
};
class ...
Predict the Output of Following C++ Program
class A {
public:
A() { cout << "A's Constructor Called " << endl; }
};
class ...
References in Functions
References are generally used for function argument
lists and function return values, just like po...
Example to Explain use of References
int* first (int* x)
{ (*x++);
return x; } // SAFE, x is outside this scope
int& secon...
Explanation of Previous Program
We have four different functions in the above program.
• first() takes a pointer as argume...
Passing parameters by References-1
// function declaration
void swap(int& x, int& y);
int main () {
// local variable decl...
Passing parameters by References-2
// function definition to swap the values
void swap(int& x, int& y) {
int temp;
//save ...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Pointer to Member Functions
• Pointers can be used to point to class's Member
functions.
• Syntax :
• We can change the va...
Example of Pointer to Member Functions
class Data
{ public:
int f (float) { return 1; }
};
int (Data::*fp1) (float) = &Dat...
How to pass objects to a function?
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Example: Pass Objects to Function-1
class Complex {
private: int real; int imag;
public:
Complex(): real(0), imag(0) { }
v...
Example: Pass Objects to Function-2
void displaySum() {
cout << "Sum = " << real<< "+" << imag << "i";
}
};
int main() {
C...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Passing Objects as Function Arguments-1
class rational {
private: int num; int dnum;
public:
rational():num(1),dnum(1) {}
...
Passing Objects as Function Arguments-2
void divide(rational r1,rational r2) {
num=r1.num*r2.dnum;
dnum=r1.dnum*r2.num;
}
...
How to return an object from the function?
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Return an Object From the Function-1
class Complex {
private: int real; int imag;
public:
Complex(): real(0), imag(0) { }
...
Return an Object From the Function-2
void displayData() {
cout << "Sum = " << real << "+" << imag << "i";
}
};
int main() ...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Function Call Binding with class Objects
• Connecting the function call to the function body is
called Binding. When it is...
Function Call Binding with class Objects
class Base {
public:
void show() {
cout << "Base Classt"; }
};
class Derived : pu...
Function Call Binding with class Objects
class Base {
public:
void show() {
cout << "Base Classt"; }
};
class Derived : pu...
Function Call Binding using Base class Pointer
• But when we use a Base class's pointer or reference
to hold Derived class...
Function Call Binding using Base class Pointer
class Base {
public:
void show() {
cout << "Base Class"; }
};
class Derived...
Function Call Binding using Base class Pointer
class Base {
public:
void show() {
cout << "Base Class"; }
};
class Derived...
C++ Operator Overloading
• Operator overloading is an important concept in
C++. It is a type of polymorphism in which an
o...
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Virtual Functions in C++
Outer Class
C++ Virtual Functions
• Virtual Function is a function in base class, which is
overrided in the derived class, and which t...
C++ Virtual Function
• If there are member functions with same name in
base class and derived class, virtual functions giv...
C++ Virtual Function
• A virtual function is a member function of class that is
declared within a base class and re-define...
Problem without Virtual Keyword
class A {
public: void display()
{ cout<<"Content of base class.n"; }
};
class B : public ...
Problem without Virtual Keyword
class A {
public: void display()
{ cout<<"Content of base class.n"; }
};
class B : public ...
Problem without Virtual Keyword
class A {
public: void display()
{ cout<<"Content of base class.n"; }
};
class B : public ...
Virtual Functions
• If we want to execute the member function of
derived class then, you can declare display( ) in the
bas...
Using Virtual Keyword Example
class A {
public: virtual void display()
{ cout<<"Content of base class.n"; }
};
class B : p...
Using Virtual Keyword Example
class A {
public: virtual void display()
{ cout<<"Content of base class.n"; }
};
class B : p...
One More Example of Virtual Keyword-1
class A
{
public:
virtual void show() {
cout<<"Hello base classn";
}
};
class B : pu...
One More Example of Virtual Keyword-2
int main()
{
A aobj;
B bobj;
A *bptr;
bptr=&aobj;
bptr->show(); // call base class f...
Your Task..
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Your Task..
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Content of first derived class.
Content of se...
Another use of Virtual Keyword
• Using Virtual Keyword and Accessing Private
Method of Derived class
• We can call private...
Accessing Private Method of Derived class
class A {
public: virtual void show() {
cout << "Base class Function n";
}
};
cl...
Accessing Private Method of Derived class
class A {
public: virtual void show() {
cout << "Base class Function n";
}
};
cl...
Abstract Class
• Abstract Class is a class which contains at least one
Pure Virtual function in it.
• Abstract classes are...
Characteristics of Abstract Class
• Abstract class cannot be instantiated, but pointers
and references of Abstract class t...
Pure Virtual Functions
• Pure virtual Functions are virtual functions with no
definition. They start with virtual keyword ...
Example of Pure Virtual Function-1
class BaseClass { //Abstract class
public:
virtual void Display1()=0; //Pure virtual fu...
Example of Pure Virtual Function-2
int main()
{
DerivedClass D;
// This will invoke Display1() method of Derived Class
D.D...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
One More Example of Pure Virtual Function-1
class Base { //Abstract base class
public:
virtual void show() = 0; //Pure Vir...
One More Example of Pure Virtual Function-2
int main()
{
Base *b;
Derived d;
b = &d;
b->show();
}
Object Oriented Programm...
Pure Virtual Function Real World Example-1
class Shape
{
protected:
double width, height;
public:
void set_data (double a,...
Pure Virtual Function Real World Example-2
class Rectangle: public Shape {
public:
double area ()
{
return (width * height...
Pure Virtual Function Real World Example-3
int main ()
{
Shape *sPtr;
Rectangle Rect;
sPtr = &Rect;
sPtr -> set_data (5,3)...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Encapsulation in C++
• Encapsulation is a process of wrapping of data and
methods in a single unit. It is achieved in C++ ...
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Templates in C++
Outer Class
Templates in C++ Programming
• Templates in C++ programming allows function or
class to work on more than one data type at...
Templates in C++ Programming
• Templates allow programmer to create a common class
or function that can be used for a vari...
Function Templates
• A function templates work in similar manner as
function but with one key difference.
• A single funct...
Function Templates
• A generic function that represents several functions
performing same task but on different data types...
Why use Function Templates
• Templates are instantiated at compile-time with
the source code.
• Templates are used less co...
How to define function template?
• A function template starts with keyword template
followed by template parameter/s insid...
How to define function template?
• So ,
• The templated type keyword specified can be
either "class" or " typename":
• tem...
Function Templates
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
template <typename T>
template prefix
t...
Example of Function Template
template <typename T>
T Sum(T n1, T n2) { // Template function
T rs;
rs = n1 + n2;
return rs;...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Function Templates
Example to show you function template use less
code than function overloading
Function Overloading Exam...
Function Overloading Example-1
#include <iostream>
using namespace std;
int square (int x)
{
return x * x;
}
double square...
Function Overloading Example-2
int main()
{
int i, ii;
double d, dd;
i = 2;
d = 2.2;
ii = square(i);
cout << "Square of In...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Function Templates
Example to show you function template use less
code than function overloading
Function Template Example...
Function Template Example-1
#include <iostream>
using namespace std;
template <typename T>
T square(T x)
{
T result;
resul...
Function Template Example-2
int main()
{
int i, ii;
double d, dd;
i = 2;
d = 2.2;
ii = square(i);
cout << "Square of Integ...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Function Templates
Function Templates with one Argument
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Square (Using Template)
template<class T>
void Square(T number)
{
cout << number * number;
}
Object Oriented Programming i...
Function Templates
Using Templates with Two or More than Arguments
Object Oriented Programming in C++
Lecture Slides By Ad...
Simple Multiplication
void multiply(int num1, double num2)
{
cout << "Result:t" << num1 * num2;
}
Object Oriented Programm...
Simple Multiplication
void multiply(data_type1 num1, data_type2 num2)
{
cout << "Result:t" << num1 * num2;
}
Object Orient...
Multiplication using Function Template
template<class T , class U>
void multiply(T a , U b) { // defining template functio...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Explanation of the Previous
• This program illustrates the use of template
function in C++. A template function multiply()...
Your Task…
Write a generic function that swaps values in two
variables. Your function should have two parameters
of the s...
Solution of Previous Problem-1
#include <iostream>
using namespace std;
template <typename T>
void swap(T *a, T *b)
{
T *t...
Solution of Previous Problem-2
int main()
{
int i=10, j=20;
cout <<"Original i: "<<i<<endl;
cout<<"Original J: "<< j << en...
Output of the Previous Program is :
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Your Home Work…
• Write a C++ program using function templates to
add two numbers of int and float data types?
Object Ori...
Thank You 
Object Oriented Programming in C++
Lecture Slides By Adil Aslam
Upcoming SlideShare
Loading in …5
×

Function in C++

5,854 views

Published on

Function in C++
Components of Function
Function Overloading in C++
Default Arguments in C++
Inline Function in C++
Nested Member Function Example
C++ Virtual Functions
Pure Virtual Functions
Function Templates
Why use Function Templates

Published in: Education
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE Format, ......................................................................................................................... ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... 1.DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/y6a5rkg5 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • can you send the presentation imgirirajgodare@gmail.com
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • kindly send me this slide to nyambatihosea@gmail.com
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • waqasahmad112@gmail.com plz mail me
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • anik4262@gmail.com mail me it please
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Function in C++

  1. 1. Functions in C++ Lecture Slides By Adil Aslam My Email Address: adilaslam5959@gmail.com Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  2. 2. Object Oriented Programming in C++ Lecture Slides By Adil Aslam About Me i am Student of BSCS My email address: adilaslam5959@gmail.com
  3. 3. Object Oriented Programming in C++ Lecture Slides By Adil Aslam Function in C++
  4. 4. Function in C++ • A function is a group of statements that together perform a specific task. Every C++ program has at least one function, which is main(). • Why use function ? • Function are used for divide a large code into module, due to this we can easily debug and maintain the code. For example if we write a calculator programs at that time we can write every logic in a separate function (For addition sum(), for subtraction sub()). Any function can be called many times. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  5. 5. Function in C++ • Advantage of Function • Creating functions in a program is beneficial. They • Avoid repetition of codes. • Increase program readability. • Divide a complex problem into many simpler problems. • Reduce chances of error. • Makes modifying a program becomes easier. • Makes unit testing possible. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  6. 6. Type of Function • There are two type of function in C++ Language. They are; • Library function or pre-define function. • User defined function. Object Oriented Programming in C++ Lecture Slides By Adil Aslam Function Library Function User-defined Function
  7. 7. Library function • Library functions are those which are predefined in C++ compiler. The implementation part of pre-defined functions is available in library files that are .lib/.obj files. .lib or .obj files are contained pre-compiled code. printf(), scanf(), clrscr(), pow() etc. are pre-defined functions. • Limitations of Library function • All predefined function are contained limited task only that is for what purpose function is designed for same purpose it should be used. • As a programmer we do not having any controls on predefined function implementation part is there in machine readable format. • In implementation whenever a predefined function is not supporting user requirement then go for user defined function. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  8. 8. User Defined Function • These functions are created by programmer according to their requirement for example suppose you want to create a function for add two number then you create a function with name sum() this type of function is called user defined function. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  9. 9. Components of Function • A function usually has three components. • They are: • Function prototype/declaration • Function definition • Function call Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  10. 10. 1-Function Prototype/Declaration • Function declaration informs the compiler about the function's name, type and number of argument it receives and type of value it returns. • Syntax for function declaration • For example, Object Oriented Programming in C++ Lecture Slides By Adil Aslam return_type function_name(parameter); //function name = display, receives a character as argument and returns nothing void display(char); //function name = sum, receives two integers as argument and returns an integer int sum(int,int); Note: At the time of function calling function must be terminated with ;
  11. 11. 2-Function definition Defining of function is nothing but give body of function that means write logic inside function body. Object Oriented Programming in C++ Lecture Slides By Adil Aslam return_type function_name(parameter) { //function body; }
  12. 12. Return type: A function may return a value. The return_type is the data type of the value the function returns.Return type parameters and returns statement are optional. Function name: Function name is the name of function it is decided by programmer or you. Parameters: This is a value which is pass in function at the time of calling of function A parameter is like a placeholder. It is optional. Function body: Function body is the collection of statements. Object Oriented Programming in C++ Lecture Slides By Adil Aslam return_type function_name(parameter) { //function body; }
  13. 13. Return Statement • Function can return values. A return statement is used to return values to the invoking function. The type of value a function can return is specified in the function prototype. A function which has void as return type don't return any value. Beside basic data type, it can return object and pointers too. A return statement is usually place at the end of function definition or inside a branching statement. • Example • In this function, the return type of sum() is int. So it returns an integer value s to the invoking function. Object Oriented Programming in C++ Lecture Slides By Adil Aslam int sum (int x, int y) { int s = x+y; return s; }
  14. 14. 3-Function call • Function call statement calls the function by matching its name and arguments. A function call can be made by using function name and providing the required parameters. • Syntax for function call • For example, Object Oriented Programming in C++ Lecture Slides By Adil Aslam function_name(); or variable=function_name(argument); display(a); s = sum(x,y);
  15. 15. Example of Function void sum(); // declaring a function a=10,b=20, c; void sum() // defining function { c=a+b; cout<<"Sum: "<<c; } int main() { sum(); // calling function } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Sum: 30
  16. 16. Functions in C++ • There are two approaches to passing argument to a function: • Call by Value • Call by Reference/Address Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  17. 17. Call by value • When a function is called, the called function creates a copy of all the arguments present in the calling statement. These new copies occupy separate memory location and the function works on these copies only. This method of calling a function is called call by value. In this method, only the value of argument is passed. So, if any changes done to those values inside the function is only visible inside the function. Their values remain unchanged outside it. • In this approach, the values are passed as function argument to the definition of function. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  18. 18. Call by value • In call by value mechanism, the called function creates a new set of variables in stack and copies the values of the arguments into them. • In call by value method, the called function creates its own copies of original values sent to it. Any changes, that are made, occur on the function’s copy of values and are not reflected back to the calling function. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  19. 19. Example of call by value-1 void swap(int x, int y) { int z; z = x; x = y; y = z; cout<<"Swapped value a is: = "<<x<<endl; cout<<"Swapped Value b is: = "<<y<<endl; cout<<"_______________________"<<endl; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  20. 20. Example of call by value-2 int main () { int a = 7, b = 4; cout<<"Original values a is: "<<a<<endl; cout<<"Original values b is: "<<b<<endl; cout<<"_____________________"<<endl; swap(a, b); cout<<"The value of a after swapped is: "<<a<<endl; cout<<"The value of b after swapped is: "<<b<<endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  21. 21. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  22. 22. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam No change the original value after call the function by using call by value method.
  23. 23. Call By Reference • In call by reference mechanism, instead of passing values to the function being called, references/pointers to the original variables are passed. • In call be reference method, the called function accesses and works with the original values using their references. Any changes, that occur, take place on the original values are reflected back to the calling code. • We also can pass the value by reference • In this case we pass the address of the variable rather than value • We use & operator for this purpose • To call by reference we can’t pass value, we have to pass memory address of variable Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  24. 24. Example of call by Reference-1 void swap(int *x, int *y) { int z; z = *x; *x = *y; *y = z; cout<<"Swapped value a is: = "<<*x<<endl; cout<<"Swapped Value b is: = "<<*y<<endl; cout<<"_______________________"<<endl; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  25. 25. Example of call by Reference-2 int main () { int a = 7, b = 4; cout<<"Original values a is: "<<a<<endl; cout<<"Original values b is: "<<b<<endl; cout<<"____________________"<<endl; swap(&a, &b); cout<<"The value of a after swapped is: "<<a<<endl; cout<<"The value of b after swapped is: "<<b<<endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  26. 26. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  27. 27. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam The original values are change because we pass the address rather than the value to function
  28. 28. Value Vs. Pass By Reference • Pass by value: • Makes copy of actual parameter • Passes copy of contents • Original variable's contents DO NOT change • During program execution, value parameter manipulates data stored in own memory space • Pass by reference: • Passes address of actual parameter • Accesses original variable's contents (via address) • Original variable's contents DO change • Returning more than one value • More efficient Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  29. 29. Function Overloading in C++ • Whenever same method name is exiting multiple times in the same class with different number of parameter or different order of parameters or different types of parameters is known as function overloading. • Why Function Overloading • Suppose we have to perform addition of given number but there can be any number of arguments, if we write function such as a(int, int)for two arguments, b(int, int, int) for three arguments then it is very difficult for you and other programmer to understand purpose or behaviors of function they can not identify purpose of function. So we use function overloading to easily figure out the program. For example above two functions we can write sum(int, int) and sum(int, int, int) using function overloading concept. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  30. 30. Function Overloading in C++ • What is overloading • Doing work in different way is called overloading. • What is function overloading • Two ore more than two function with same name and with different signature is called function overloading. • Signature may be vary on the basis of number of argument or data type of argument or order of argument. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  31. 31. Function Overloading (Syntax) class class_Name { Returntype method() { ........... ........... } Returntype method(datatype1 variable1) { ........... ........... } Returntype method(datatype1 variable1, datatype2 variable2) { ........... ........... } }; Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  32. 32. Function Overloading in C++ • These functions having different number or type (or both) of parameters are known as overloaded functions. For example: • Here, all 4 functions are overloaded functions because argument(s) passed to these functions are different. • Notice that, the return type of all these 4 functions are not same. Overloaded functions may or may not have different return type but it should have different argument(s). Object Oriented Programming in C++ Lecture Slides By Adil Aslam int test() { } int test(int a) { } float test(double a) { } int test(int a, double b) { }
  33. 33. Function Overloading in C++ • The number and type of arguments passed to these two functions are same even though the return type is different. Hence, the compiler will throw error. Object Oriented Programming in C++ Lecture Slides By Adil Aslam // Error code int test(int a) { } double test(int b){ }
  34. 34. Function Overloading in C++ • Different ways to overload the method • There are two ways to overload the method in C++: • By changing number of arguments or parameters • By changing the data type Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  35. 35. By Changing Number of Arguments class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(int a, int b, int c) { cout<<a+b+c; } }; int main() { Addition obj; obj.sum(10, 20); //Calling the function having two Parameters cout<<endl; obj.sum(10, 20, 30); //Calling the function having three Parameters } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  36. 36. By Changing Number of Arguments class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(int a, int b, int c) { cout<<a+b+c; } }; int main() { Addition obj; obj.sum(10, 20); //Calling the function having two Parameters cout<<endl; obj.sum(10, 20, 30); //Calling the function having three Parameters } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Both Function Having Different Parameters
  37. 37. By Changing Number of Arguments class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(int a, int b, int c) { cout<<a+b+c; } }; int main() { Addition obj; obj.sum(10, 20); //Calling the function having two Parameters cout<<endl; obj.sum(10, 20, 30); //Calling the function having three Parameters } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Both Functions Having Same Name
  38. 38. By Changing Number of Arguments class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(int a, int b, int c) { cout<<a+b+c; } }; int main() { Addition obj; obj.sum(10, 20); //Calling the function having two Parameters cout<<endl; obj.sum(10, 20, 30); //Calling the function having three Parameters } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Function with Two Parameters
  39. 39. By Changing Number of Arguments class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(int a, int b, int c) { cout<<a+b+c; } }; int main() { Addition obj; obj.sum(10, 20); //Calling the function having two Parameters cout<<endl; obj.sum(10, 20, 30); //Calling the function having three Parameters } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Function with Three Parameters
  40. 40. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  41. 41. By Changing the Data Type class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(float a, float b) { cout<<a+b; } }; int main() { Addition obj; obj.sum(10, 20); cout<<endl; obj.sum(30, 40); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  42. 42. By Changing the Data Type class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(float a, float b) { cout<<a+b; } }; int main() { Addition obj; obj.sum(10, 20); cout<<endl; obj.sum(30, 40); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Function Parameters having integer data type
  43. 43. By Changing the Data Type class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(float a, float b) { cout<<a+b; } }; int main() { Addition obj; obj.sum(10, 20); cout<<endl; obj.sum(30, 40); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Function Parameters having Float data type
  44. 44. By Changing the Data Type class Addition { public: void sum(int a, int b) { cout<<a+b; } void sum(float a, float b) { cout<<a+b; } }; int main() { Addition obj; obj.sum(10, 20); cout<<endl; obj.sum(30, 40); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Both Functions having same number of Parameters
  45. 45. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  46. 46. int absolute(int); float absolute(float); int main() { int a = -5; float b = 5.5; cout << "Absolute value of " << a << " = " << absolute(a) << endl; cout << "Absolute value of " << b << " = " << absolute(b); return 0; } int absolute(int var) { if (var < 0) var = -var; return var; } float absolute(float var){ if (var < 0.0) var = -var; return var; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Function Overloading Absolute value of -5 = 5 Absolute value of 5.5 = 5.5
  47. 47. Explanation of Previous Program • In the previous example, two functions absolute() are overloaded. • Both functions take single argument. However, one function takes integer as an argument and other takes float as an argument. • When absolute() function is called with integer as an argument, this function is called: • When absolute() function is called with float as an argument, this function is called: Object Oriented Programming in C++ Lecture Slides By Adil Aslam int absolute(int var) { if (var < 0) var = -var; return var; } float absolute(float var){ if (var < 0.0) var = -var; return var; }
  48. 48. Function Overloading in C++ Note: The scope of overloading is within the class. • Can we overload constructor in C++ • Yes We can overload constructor also Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  49. 49. Your Task… ..1 class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } void print(char* c) { cout << "Printing character: " << c << endl; } }; Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  50. 50. Your Task… ..2 int main() { printData pd; // Call print to print integer pd.print(5); // Call print to print float pd.print(222.111); // Call print to print character pd.print("Adil Aslam"); return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  51. 51. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  52. 52. Default Arguments • When we mention a default value for a parameter while declaring the function, it is said to be as default argument. In this case, even if we make a call to the function without passing any value for that parameter, the function will take the default value specified. • Here we have provided a default value for y, during function definition. Object Oriented Programming in C++ Lecture Slides By Adil Aslam sum(int x,int y=0) { cout << x+y; } int main(){ sum(10); sum(10,0); sum(10,10); }
  53. 53. Default Arguments void sum(int x,int y=0,int z=0) { cout << x+y+z<<endl; } int main() { sum(10); sum(10,0); sum(10,20); sum(10,0,0); sum(10,20,30); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  54. 54. Default Arguments void sum(int x,int y=0,int z=0) { cout << x+y+z<<endl; } int main() { sum(10); sum(10,0); sum(10,20); sum(10,0,0); sum(10,20,30); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam 10 10 30 10 60
  55. 55. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  56. 56. One Example of default argument value int Add(int x, int y=20, int z=30) { return x + y + z; } int main() { int rs; rs = Add(5); cout<<"ntThe sum is : "<<rs; rs = Add(4,8); cout<<"ntThe sum is : "<<rs; rs = Add(7,3,4); cout<<"ntThe sum is : "<<rs; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Function Declaration with two Default Values
  57. 57. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  58. 58. Rules for using Default Arguments • Only the last argument must be given default value. You cannot have a default argument followed by non-default argument. • If we default an argument, then you will have to default all the subsequent arguments after that. • We can give any value a default value to argument, compatible with its datatype. Object Oriented Programming in C++ Lecture Slides By Adil Aslam sum (int x , int y); sum (int x , int y=0); sum (int x=0, int y); // This is Incorrect sum (int x , int y=0); sum (int x , int y=0 , int z); // This is incorrect sum (int x , int y=10 , int z=10); // Correct
  59. 59. Placeholder Arguments • When arguments in a function are declared without any identifier they are called placeholder arguments. • Such arguments can also be used with default arguments. Object Oriented Programming in C++ Lecture Slides By Adil Aslam void sum (int , int); void cube(double , double , double) void sum (int , int=0); void cube(double , double=10 , double=20)
  60. 60. Inline Function in C++ • Inline Function is powerful concept in C++ programming language. 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. • To make any function inline function just preceded that function with inline keyword. • Why use Inline function • Whenever we call any function many time then, it take a lot of extra time in execution of series of instructions such as saving the register, pushing arguments, returning to calling function. For solve this problem in C++ introduce inline function. • Advantage of Inline Function • The main advantage of inline function is it make the program faster. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  61. 61. Inline Function in C++ • An inline function is a combination of macro & function. At the time of declaration or definition, function name is preceded by word inline. • Function calls involve execution-time overhead. • Inline functions to help reduce function call overhead, especially for small functions • When inline functions area used, the overhead of function call is eliminated. Instead, the executable statements of the function are copied at the place of each function call. This is done by the compiler. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  62. 62. Inline Function in C++ • Inline functions provide following advantages: • Function call overhead doesn’t occur. • It speeds up your program by avoiding function calling overhead. • It save overhead of return call from a function. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  63. 63. Inline Function in C++ • Compiler may not perform inlining in such circumstances like: • If a function contains a loop. (for, while, do-while) • If a function contains static variables. • If a function is recursive. • If a function return type is other than void, and the return statement doesn’t exist in function body. • If a function contains switch or goto statement. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  64. 64. Inline Function in C++ • Some important points to be noted • Function is made inline by putting a word inline in the beginning. • Inline function should be declared before main() function. • Only shorter code is used in inline function If longer code is made inline then compiler ignores the request and it will be executed as normal function. • Hence, it is advice to define large functions outside the class definition using scope resolution :: operator, because if we define such functions inside class definition, then they become inline automatically. • Inline functions are kept in the Symbol Table by the compiler, and all the call for such functions is taken care at compile time. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  65. 65. Inline Function in C++ • When to use Inline functions • Function can be made as inline as per programmer need. Some useful recommendation are mentioned below: • 1. Use inline function when performance is needed. • 2. Use inline function over macros. • 3. Prefer to use inline keyword outside the class with the function definition to hide implementation details. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  66. 66. Inline Function in C++ • Syntax • Example Object Oriented Programming in C++ Lecture Slides By Adil Aslam inline data_type function_name() { //function body } inline void show() { //function body }
  67. 67. Example of Inline Function inline void show() { cout<<"Hello World"; } int main() { show(); // Call it like a normal function } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  68. 68. Example of Inline Function inline void show() { cout<<"Hello World"; } int main() { show(); // Call it like a normal function } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Inline Function Hello World
  69. 69. Another Example of inline Function 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,50): " << Max(-100,50) << endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  70. 70. Another Example of inline Function 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,50): " << Max(-100,50) << endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Using Conditional Ternary Operator Here
  71. 71. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  72. 72. Inline Functions • Limitations of Inline Functions • Large Inline functions cause Cache misses and affect performance negatively. • Compilation overhead of copying the function body everywhere in the code on compilation, which is negligible for small programs, but it makes a difference in large code bases. • Also, if we require address of the function in program, compiler cannot perform inlining on such functions. Because for providing address to a function, compiler will have to allocate storage to it. But inline functions doesn't get storage, they are kept in Symbol table. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  73. 73. Nested Member Function of a Class • We just discussed that a function of a class can be called only by an object of that class using dot (.) operator. However is an exception to this, A member function can be called by using its b=name inside another member function of the same class. Tis is known as nesting of member functions. • Let’s see an example in next slide that illustrates this feature Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  74. 74. Nested Member Function Example-1 class comparing { int m , n; public: void input(void); void display(void); int larger(void); }; void comparing :: input(void) { cout << "Enter the two numbers to be compared n"; cin >> m >> n; } void comparing :: display(void) { cout << "The larger number among the entered values is :“ << larger() << endl; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Calling Member Function
  75. 75. Nested Member Function Example-2 int comparing :: larger(void) { if (m >= n) { return (m); } else { return (n); } } int main () { comparing x; x.input(); x.display(); return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  76. 76. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  77. 77. Static Member Functions • These functions work for the class as whole rather than for a particular object of a class. • It can be called using an object and the direct member access . operator. But, its more typical to call a static member function by itself, using class name and scope resolution :: operator. • static member function called by :: inplace of . operator. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  78. 78. Static Member Functions Example class A { public: static void f() { cout<<"n My Name is Adil Aslam"; } }; int main() { A::f(); // calling member function directly with class name } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  79. 79. Static Member Functions Example class A { public: static void f() { cout<<"n My Name is Adil Aslam"; } }; int main() { A::f(); // calling member function directly with class name } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Static Member Function
  80. 80. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  81. 81. Static Member Functions Example class A { public: void f() { cout<<"n My Name is Adil Aslam"; } }; int main() { A::f(); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Without Static Keyword
  82. 82. Compiler View Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  83. 83. Compiler View Object Oriented Programming in C++ Lecture Slides By Adil Aslam These functions cannot access ordinary data members and member functions, but only static data members and static member functions.
  84. 84. Another Example of Static Member Functions-1 class Box { public: static int objectCount; //Static Data Member // Constructor definition Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume() { //Normal function return length * breadth * height; } static int getCount() { //Static member function return objectCount; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  85. 85. Another Example of Static Member Functions-2 private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main() { // Print total number of objects before creating object. cout << "Initial Stage Count: " << Box::getCount() << endl; Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects after creating object. cout << "Final Stage Count: " << Box::getCount() << endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  86. 86. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  87. 87. Predict the Output of Following C++ Program class A { public: A() { cout << "A's Constructor Called " << endl; } }; class B { static A a; public: B() { cout << "B's Constructor Called " << endl; } }; int main() { B b; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  88. 88. Predict the Output of Following C++ Program class A { public: A() { cout << "A's Constructor Called " << endl; } }; class B { static A a; public: B() { cout << "B's Constructor Called " << endl; } }; int main() { B b; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam B's Constructor Called The above program calls only B’s constructor, it doesn’t call A’s constructor. The reason for this is simple, static members are only declared in class declaration, not defined. They must be explicitly defined outside the class using scope resolution operator.
  89. 89. References in Functions References are generally used for function argument lists and function return values, just like pointers. Rules for using Reference in Functions: • When we use reference in argument list, we must keep in mind that any change to the reference inside the function will cause change to the original argument outside the function. • When we return a reference from a function, you should see that whatever the reference is connected to shouldn't go out of scope when function ends. Either make that global or static Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  90. 90. Example to Explain use of References int* first (int* x) { (*x++); return x; } // SAFE, x is outside this scope int& second (int& x) { x++; return x; } // SAFE, x is outside this scope int& third () { int q; return q; } // ERROR, scope of q ends here int& fourth () { static int x; return x; } // SAFE, x is static, hence lives till the end. int main() { int a=0; first(&a); // UGLY and explicit second(a); // CLEAN and hidden } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  91. 91. Explanation of Previous Program We have four different functions in the above program. • first() takes a pointer as argument and returns a pointer, it will work fine. The returning pointer points to variable declared outside first(), hence it will be valid even after the first() ends. • Similarly, second() will also work fine. The returning reference is connected to valid storage, that is int a in this case. • But in case of third(), we declare a variable q inside the function and try to return a reference connected to it. But as soon as function third() ends, the local variable q is destroyed, hence nothing is returned. • To remodify above problem, we make x as static in function fourth(), giving it a lifetime till main() ends, hence now a reference connected to x will be valid when returned. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  92. 92. Passing parameters by References-1 // function declaration void swap(int& x, int& y); int main () { // local variable declaration: int a = 111; int b = 2222; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl; // calling a function to swap the values swap(a, b); cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  93. 93. Passing parameters by References-2 // function definition to swap the values void swap(int& x, int& y) { int temp; //save the value at address x temp = x; //put y into x x = y; //put x into y y = temp; return; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  94. 94. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  95. 95. Pointer to Member Functions • Pointers can be used to point to class's Member functions. • Syntax : • We can change the value and behaviour of these pointers on runtime. That means, you can point it to other member function or member variable. • To have pointer to data member and member functions you need to make them public. Object Oriented Programming in C++ Lecture Slides By Adil Aslam return_type (class_name::*ptr_name) (argument_type) = &class_name::function_name ;
  96. 96. Example of Pointer to Member Functions class Data { public: int f (float) { return 1; } }; int (Data::*fp1) (float) = &Data::f; // Declaration and assignment int (Data::*fp2) (float); // Only Declaration int main() { fp2 = &Data::f; // Assignment inside main() } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  97. 97. How to pass objects to a function? Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  98. 98. Example: Pass Objects to Function-1 class Complex { private: int real; int imag; public: Complex(): real(0), imag(0) { } void readData() { cout << "Enter real and imaginary number respectively:"<<endl; cin >> real >> imag; } void addComplexNumbers(Complex comp1, Complex comp2) { // real represents the real data of object c3 because this function is called using code c3.add(c1,c2); real=comp1.real+comp2.real; // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2); imag=comp1.imag+comp2.imag; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  99. 99. Example: Pass Objects to Function-2 void displaySum() { cout << "Sum = " << real<< "+" << imag << "i"; } }; int main() { Complex c1,c2,c3; c1.readData(); c2.readData(); c3.addComplexNumbers(c1, c2); //Passing object to function c3.displaySum(); return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  100. 100. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  101. 101. Passing Objects as Function Arguments-1 class rational { private: int num; int dnum; public: rational():num(1),dnum(1) {} void get () { cout<<"Enter Numerator: "; cin>>num; cout<<"Enter Denominator: "; cin>>dnum; } void print () { cout<<num<<"/"<<dnum<<endl; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  102. 102. Passing Objects as Function Arguments-2 void divide(rational r1,rational r2) { num=r1.num*r2.dnum; dnum=r1.dnum*r2.num; } }; int main () { rational r1,r2,r3; r1.get(); r3.divide(r1,r2); r3.print(); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Enter Numerator: 8 Enter Denominator: 4 8/4
  103. 103. How to return an object from the function? Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  104. 104. Return an Object From the Function-1 class Complex { private: int real; int imag; public: Complex(): real(0), imag(0) { } void readData() { cout << "Enter real and imaginary number respectively:"<<endl; cin >> real >> imag; } Complex addComplexNumbers(Complex comp2) { Complex temp; // real represents the real data of object c3 because this function is called using code c3.add(c1,c2); temp.real = real+comp2.real; // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2); temp.imag = imag+comp2.imag; return temp; //Return object from function } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  105. 105. Return an Object From the Function-2 void displayData() { cout << "Sum = " << real << "+" << imag << "i"; } }; int main() { Complex c1, c2, c3; c1.readData(); c2.readData(); c3 = c1.addComplexNumbers(c2); c3.displayData(); return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  106. 106. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  107. 107. Function Call Binding with class Objects • Connecting the function call to the function body is called Binding. When it is done before the program is run, its called Early Binding or Static Binding or Compile-time Binding. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  108. 108. Function Call Binding with class Objects class Base { public: void show() { cout << "Base Classt"; } }; class Derived : public Base { public: void show() { cout << "Derived Class"; } }; int main() { Base b; //Base class object Derived d; //Derived class object b.show(); //Early Binding Occurs d.show(); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  109. 109. Function Call Binding with class Objects class Base { public: void show() { cout << "Base Classt"; } }; class Derived : public Base { public: void show() { cout << "Derived Class"; } }; int main() { Base b; //Base class object Derived d; //Derived class object b.show(); //Early Binding Occurs d.show(); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam In this example, we are calling the overrided function using Base class and Derived class object. Base class object will call base version of the function and derived class's object will call the derived version of the function. Base class Derived Class
  110. 110. Function Call Binding using Base class Pointer • But when we use a Base class's pointer or reference to hold Derived class's object, then Function call Binding gives some unexpected results. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  111. 111. Function Call Binding using Base class Pointer class Base { public: void show() { cout << "Base Class"; } }; class Derived : public Base { public: void show() { cout << "Derived Class"; } }; int main() { Base* b; //Base class pointer Derived d; //Derived class object b = &d; b->show(); //Early Binding Occurs } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  112. 112. Function Call Binding using Base class Pointer class Base { public: void show() { cout << "Base Class"; } }; class Derived : public Base { public: void show() { cout << "Derived Class"; } }; int main() { Base* b; //Base class pointer Derived d; //Derived class object b = &d; b->show(); //Early Binding Occurs } Object Oriented Programming in C++ Lecture Slides By Adil Aslam In the example, although, the object is of Derived class, still Base class's method is called. This happens due to Early Binding. Compiler on seeing Base class's pointer, set call to Base class's show() function, without knowing the actual object type. & operator use for reference Base Class
  113. 113. C++ Operator Overloading • Operator overloading is an important concept in C++. It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type. • The meaning of operators are already defined and fixed for basic types like: int, float, double etc in C++ language. For example: If you want to add two integers then, + operator is used. But, for user- defined types(like: objects), you can define the meaning of operator, i.e., you can redefine the way that operator works. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  114. 114. Object Oriented Programming in C++ Lecture Slides By Adil Aslam Virtual Functions in C++ Outer Class
  115. 115. C++ Virtual Functions • Virtual Function is a function in base class, which is overrided in the derived class, and which tells the compiler to perform Late Binding on this function. • Virtual Keyword is used to make a member function of the base class Virtual. • Late Binding • In Late Binding function call is resolved at runtime. Hence, now compiler determines the type of object at runtime, and then binds the function call. Late Binding is also called Dynamic Binding or Runtime Binding. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  116. 116. C++ Virtual Function • If there are member functions with same name in base class and derived class, virtual functions gives programmer capability to call member function of different class by a same function call depending upon different context. This feature in C++ programming is known as polymorphism which is one of the important feature of OOP. • If a base class and derived class has same function and if you write code to access that function using pointer of base class then, the function in the base class is executed even if, the object of derived class is referenced with that pointer variable. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  117. 117. C++ Virtual Function • A virtual function is a member function of class that is declared within a base class and re-defined in derived class. • When you want to use same function name in both the base and derived class, then the function in base class is declared as virtual by using the virtual keyword and again re-defined this function in derived class without using virtual keyword. • Syntax Object Oriented Programming in C++ Lecture Slides By Adil Aslam virtual return_type function_name() { ....... ....... }
  118. 118. Problem without Virtual Keyword class A { public: void display() { cout<<"Content of base class.n"; } }; class B : public A { public: void display() { cout<<"Content of derived class.n"; } }; int main() { A *b; //declare pointer variables of type B B d; //create the object d of type D b = &d; //Store Address of object d in pointer variable b->display(); // try to calling display function of Derived Class return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  119. 119. Problem without Virtual Keyword class A { public: void display() { cout<<"Content of base class.n"; } }; class B : public A { public: void display() { cout<<"Content of derived class.n"; } }; int main() { A *b; //declare pointer variables of type B B d; //create the object d of type D b = &d; //Store Address of object d in pointer variable b->display(); // try to calling display function of Derived Class return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Note: An object(either normal or pointer) of derived class is type compatible with pointer to base class. So, b = &d; is allowed in this program. Early Binding Occur
  120. 120. Problem without Virtual Keyword class A { public: void display() { cout<<"Content of base class.n"; } }; class B : public A { public: void display() { cout<<"Content of derived class.n"; } }; int main() { A *b; //declare pointer variables of type B B d; //create the object d of type D b = &d; //Store Address of object d in pointer variable b->display(); // try to calling display function of Derived Class return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Content of base class. In this program, even if the object of derived class d is put in pointer to base class, display( ) of the base class is executed( member function of the class that matches the type of pointer ).
  121. 121. Virtual Functions • If we want to execute the member function of derived class then, you can declare display( ) in the base class virtual which makes that function existing in appearance only but, you can't call that function. In order to make a function virtual, you have to add keyword virtual in front of a function. • Let see an example in next slide. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  122. 122. Using Virtual Keyword Example class A { public: virtual void display() { cout<<"Content of base class.n"; } }; class B : public A { public: void display() { cout<<"Content of derived class.n"; } }; int main() { A *b; //Base class pointer B d; //Derived class object b = &d; b->display(); //Late Binding Occurs return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  123. 123. Using Virtual Keyword Example class A { public: virtual void display() { cout<<"Content of base class.n"; } }; class B : public A { public: void display() { cout<<"Content of derived class.n"; } }; int main() { A *b; //Base class pointer B d; //Derived class object b = &d; b->display(); //Late Binding Occurs return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam On using Virtual keyword with Base class's function, Late Binding takes place and the derived version of function will be called, because base class pointer pointes to Derived class object. Content of derived class.
  124. 124. One More Example of Virtual Keyword-1 class A { public: virtual void show() { cout<<"Hello base classn"; } }; class B : public A { public: void show() { cout<<"Hello derive class"; } }; Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  125. 125. One More Example of Virtual Keyword-2 int main() { A aobj; B bobj; A *bptr; bptr=&aobj; bptr->show(); // call base class function bptr=&bobj; bptr->show(); // call derive class function } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Hello base class Hello derive class
  126. 126. Your Task.. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  127. 127. Your Task.. Object Oriented Programming in C++ Lecture Slides By Adil Aslam Content of first derived class. Content of second derived class.
  128. 128. Another use of Virtual Keyword • Using Virtual Keyword and Accessing Private Method of Derived class • We can call private function of derived class from the base class pointer with the help of virtual keyword. Compiler checks for access specifier only at compile time. So at run time when late binding occurs it does not check whether we are calling the private function or public function. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  129. 129. Accessing Private Method of Derived class class A { public: virtual void show() { cout << "Base class Function n"; } }; class B: public A { private: virtual void show() { cout << "Derived class Functionn"; } }; int main() { A *a; //Base class pointer B b; //Derived class object a = &b; a -> show(); //Late Binding Occurs } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  130. 130. Accessing Private Method of Derived class class A { public: virtual void show() { cout << "Base class Function n"; } }; class B: public A { private: virtual void show() { cout << "Derived class Functionn"; } }; int main() { A *a; //Base class pointer B b; //Derived class object a = &b; a -> show(); //Late Binding Occurs } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Private Member Function of Derived class with Virtual Keyword Derived class Function
  131. 131. Abstract Class • Abstract Class is a class which 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. • A class with at least one pure virtual function or abstract function is called abstract class. • Pure virtual function is also known as abstract function Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  132. 132. Characteristics of Abstract Class • Abstract class cannot be instantiated, but pointers and references of Abstract class type can be created. • Abstract class can have normal functions and variables along with a pure virtual function. • Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface. • Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will become Abstract too. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  133. 133. Pure Virtual Functions • Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and ends with = 0. Here is the syntax for a pure virtual function, • Syntax • A class which have pure virtual function is called abstract class in cpp. • We can not create object of abstract class so we need to create sub class of abstract class to use that function. Object Oriented Programming in C++ Lecture Slides By Adil Aslam virtual void display()=0;
  134. 134. Example of Pure Virtual Function-1 class BaseClass { //Abstract class public: virtual void Display1()=0; //Pure virtual function or abstract function virtual void Display2()=0; //Pure virtual function or abstract function void Display3() { cout<<"ntThis is Display3() method of Base Class"; } }; class DerivedClass : public BaseClass { public: void Display1() { cout<<"ntThis is Display1() method of Derived Class"; } void Display2() { cout<<"ntThis is Display2() method of Derived Class"; } }; Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  135. 135. Example of Pure Virtual Function-2 int main() { DerivedClass D; // This will invoke Display1() method of Derived Class D.Display1(); // This will invoke Display2() method of Derived Class D.Display2(); // This will invoke Display3() method of Base Class D.Display3(); return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  136. 136. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  137. 137. One More Example of Pure Virtual Function-1 class Base { //Abstract base class public: virtual void show() = 0; //Pure Virtual Function }; void Base :: show() //Pure Virtual definition { cout << "Pure Virtual definition n"; } class Derived : public Base { public: void show() { cout << "Implementation of Virtual Function in Derived class"; } }; Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  138. 138. One More Example of Pure Virtual Function-2 int main() { Base *b; Derived d; b = &d; b->show(); } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Pure Virtual definition Implementation of Virtual Function in Derived class
  139. 139. Pure Virtual Function Real World Example-1 class Shape { protected: double width, height; public: void set_data (double a, double b) { width = a; height = b; } virtual double area() = 0; }; Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  140. 140. Pure Virtual Function Real World Example-2 class Rectangle: public Shape { public: double area () { return (width * height); } }; class Triangle: public Shape { public: double area () { return (width * height)/2; } }; Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  141. 141. Pure Virtual Function Real World Example-3 int main () { Shape *sPtr; Rectangle Rect; sPtr = &Rect; sPtr -> set_data (5,3); cout << "Area of Rectangle is " << sPtr -> area() << endl; Triangle Tri; sPtr = &Tri; sPtr -> set_data (4,6); cout << "Area of Triangle is " << sPtr -> area() << endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  142. 142. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  143. 143. Encapsulation in C++ • Encapsulation is a process of wrapping of data and methods in a single unit. It is achieved in C++ language by class concept. • Combining of state and behavior in a single container is known as encapsulation. In C++ language encapsulation can be achieve using class keyword, state represents declaration of variables on attributes and behavior represents operations in terms of method. • Advantage of Encapsulation • The main advantage of using of encapsulation is to secure the data from other methods, when we make a data private then these data only use within the class, but these data not accessible outside the class. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  144. 144. Object Oriented Programming in C++ Lecture Slides By Adil Aslam Templates in C++ Outer Class
  145. 145. Templates in C++ Programming • Templates in C++ programming allows function or class to work on more than one data type at once without writing different codes for different data types. Templates are often used in larger programs for the purpose of code reusability and flexibility of program. The concept of templates can be used in two different ways: • Function Templates • Class Templates • As of C++ 11, Variable Template has also been added. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  146. 146. Templates in C++ Programming • Templates allow programmer to create a common class or function that can be used for a variety of data types. The parameters used during its definition is of generic type and can be replaced later by actual parameters. This is known as the concept of generic programming. The main advantage of using a template is the reuse of same algorithm for various data types, hence saving time from writing similar codes. • For example, consider a situation where we have to sort a list of students according to their roll number and their percentage. Since, roll number is of integer type and percentage is of float type, we need to write separate sorting algorithm for this problem. But using template, we can define a generic data type for sorting which can be replaced later by integer and float data type. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  147. 147. Function Templates • A function templates work in similar manner as function but with one key difference. • A single function template can work on different types at once but, different functions are needed to perform identical task on different data types. • If you need to perform identical operations on two or more types of data then, you can use function overloading. But better approach would be to use function templates because you can perform this task by writing less code and code is easier to maintain. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  148. 148. Function Templates • A generic function that represents several functions performing same task but on different data types is called function template. • For example, a function to add two integer and float numbers requires two functions. One function accept integer types and the other accept float types as parameters even though the functionality is the same. Using a function template, a single function can be used to perform both additions. It avoids unnecessary repetition of code for doing same task on various data types. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  149. 149. Why use Function Templates • Templates are instantiated at compile-time with the source code. • Templates are used less code than overloaded C++ functions. • Templates are type safe. • Templates allow user-defined specialization. • Templates allow non-type parameters. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  150. 150. How to define function template? • A function template starts with keyword template followed by template parameter/s inside <> which is followed by function declaration. • T is a template argument and class is a keyword. • We can also use keyword typename instead of class. • When, an argument is passed to some_function( ), compiler generates new version of some_function() to work on argument of that type. Object Oriented Programming in C++ Lecture Slides By Adil Aslam template <class T> T some_function(T argument) { .... ... .... }
  151. 151. How to define function template? • So , • The templated type keyword specified can be either "class" or " typename": • template<class T> • template<typename T> • Both are valid and behave exactly the same. I prefer "typename". Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  152. 152. Function Templates Object Oriented Programming in C++ Lecture Slides By Adil Aslam template <typename T> template prefix type parameter
  153. 153. Example of Function Template template <typename T> T Sum(T n1, T n2) { // Template function T rs; rs = n1 + n2; return rs; } int main() { int A=10,B=20,C; long I=11,J=22,K; C = Sum(A,B); // Calling template function cout<<"nThe sum of integer values : "<<C; K = Sum(I,J); // Calling template function cout<<"nThe sum of long values : "<<K; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  154. 154. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  155. 155. Function Templates Example to show you function template use less code than function overloading Function Overloading Example Object Oriented Programming in C++ Lecture Slides By Adil Aslam Overloaded functions specified for each data type
  156. 156. Function Overloading Example-1 #include <iostream> using namespace std; int square (int x) { return x * x; } double square (double x) { return x * x; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  157. 157. Function Overloading Example-2 int main() { int i, ii; double d, dd; i = 2; d = 2.2; ii = square(i); cout << "Square of Integer Number "<< " : " << ii << endl; dd = square(d); cout<< "Square of double number "<< " : " << dd << endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  158. 158. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  159. 159. Function Templates Example to show you function template use less code than function overloading Function Template Example Object Oriented Programming in C++ Lecture Slides By Adil Aslam A single template to support all data types
  160. 160. Function Template Example-1 #include <iostream> using namespace std; template <typename T> T square(T x) { T result; result = x * x; return result; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  161. 161. Function Template Example-2 int main() { int i, ii; double d, dd; i = 2; d = 2.2; ii = square(i); cout << "Square of Integer Number "<< ": " << ii << endl; dd = square(d); cout<< "Square of double number "<< " : " << dd << endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  162. 162. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  163. 163. Function Templates Function Templates with one Argument Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  164. 164. Square (Using Template) template<class T> void Square(T number) { cout << number * number; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam void Square(data_type number) { cout << number * number; } Single Argument
  165. 165. Function Templates Using Templates with Two or More than Arguments Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  166. 166. Simple Multiplication void multiply(int num1, double num2) { cout << "Result:t" << num1 * num2; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam void multiply(double num1, int num2) { cout << "Result:t" << num1 * num2; }
  167. 167. Simple Multiplication void multiply(data_type1 num1, data_type2 num2) { cout << "Result:t" << num1 * num2; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam Multiplication (Using Template) template<class T, class U> void multiply(T num1, U num2) { cout << "Result:t" << num1 * num2; }
  168. 168. Multiplication using Function Template template<class T , class U> void multiply(T a , U b) { // defining template function cout<<"Multiplication= "<<a*b<<endl; } int main() { int a,b; float x,y; cout<<"Enter two integer data: "<<endl; cin>>a>>b; cout<<"Enter two float data: "<<endl; cin>>x>>y; multiply(a,b); // Multiply two integer type data multiply(x,y); // Multiply two float type data multiply(a,x); // Multiply a float and integer type data return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  169. 169. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  170. 170. Explanation of the Previous • This program illustrates the use of template function in C++. A template function multiply() is created which accepts two arguments and multiply them. The type of argument is not defined until the function is called. This single function is used to multiply two data of integer type, float type and, integer and float type. We don't need to write separate functions for different data types. In this way, a single function can be used to process data of various type using function template. • Also we use template with two arguments Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  171. 171. Your Task… Write a generic function that swaps values in two variables. Your function should have two parameters of the same type. Test the function with int, double and string values. Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  172. 172. Solution of Previous Problem-1 #include <iostream> using namespace std; template <typename T> void swap(T *a, T *b) { T *temp; temp = a; a = b; b = temp; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  173. 173. Solution of Previous Problem-2 int main() { int i=10, j=20; cout <<"Original i: "<<i<<endl; cout<<"Original J: "<< j << endl; cout<<"_________________"<<endl<<endl; swap(i,j); // swapping integers cout <<"Swapped i: "<<i<<endl; cout<<"Swapped J: "<< j << endl; return 0; } Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  174. 174. Output of the Previous Program is : Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  175. 175. Your Home Work… • Write a C++ program using function templates to add two numbers of int and float data types? Object Oriented Programming in C++ Lecture Slides By Adil Aslam
  176. 176. Thank You  Object Oriented Programming in C++ Lecture Slides By Adil Aslam

×