SlideShare une entreprise Scribd logo
1  sur  11
Lecture 06



         Reference Variables


Learn about:
- Reference arguments
- Pass Arguments and Structures by reference
- const function arguments

Ref.: OOP using C++, Joyce Farrel, Thopson Learningv



                                                       1
Reference Variables (page 137-139)

• A reference is an alias (a different name) to a variable.
• How to declare a reference variable?
  i) By placing a type and & in front of a variable.
  ii) Assign another variable of the same type to the
  reference variable.
    For example:         double someMoney;
                         double &cash = someMoney



                                                 2/11
Reference Variables (page 137-139)

double someMoney;
double &cash = someMOney;

cash = 6.78;
cout<<cash<<endl;   // displays 6.78
cout<<someMoney;    // displays 6.78

someMOney = 111.333;
cout<<cash<<endl;    // displays 111.333
cout<<someMoney;     // displays 111.333

                                       3/11
Reference Arguments

• Passing arguments by reference allows a function to
  access variables in the calling program, as well as
  returning more than one value.


• Reference arguments are indicated by the & following
  the data type.

    (float n, float &intp, float &fracp)


                                              4/11
Reference Arguments
                         Example 1
#include <iostream.h>
void intfrac(float n, float& intp, float& fracp)
{ long temp = static_cast<long>(n); // temp = 10
  intp = static_cast<float>(temp);   // intp = 10
  fracp = n - intp;                  // fracp = 0.25
}
void main()
{ float number, intpart, fracpart;
  do {
    cout << "nEnter a real number: ";
    cin>>number;        // input: 10.25
    intfrac(number, intpart, fracpart);
    cout << "Integer part is " << intpart
         << ", fraction part is "
         << fracpart << endl;
  } while( number != 0.0 );
                                               5/11
}
Reference Arguments
                        Example 1 (cont.)


• The & indicates that intp is an alias for whatever variable is
 passed as an argument. Similarly for fracp.

• Note that the & is not used in the function call.

• Do not confuse with the address     of operator (same symbol).




                                                      6/11
Pass By Reference: Example 2

#include <iostream.h>
void order(int& numb1,   int& numb2)
{ if(numb1 > numb2) {
    int temp = numb1;
    numb1 = numb2;
    numb2 = temp; }
}
void main()
{ int n1=99, n2=11;       // not ordered
   int n3=22, n4=88;      // ordered
   order(n1, n2);
   order(n3, n4);
   cout << "n1=" << n1   <<   endl;
   cout << "n2=" << n2   <<   endl;
   cout << "n3=" << n3   <<   endl;
   cout << "n4=" << n4   <<   endl;        7/11
}
Passing Structures By Reference
                   Example
#include <iostream.h>
struct Distance {     // English distance
   int feet;
   float inches;
};

void engldisp( Distance dd )
{
  cout << dd.feet << "'-"
       << dd.inches << """;
}

void scale( Distance& dd, float factor)
{
  float inches = (dd.feet*12 + dd.inches) * factor;
  dd.feet = static_cast<int>(inches / 12);
  dd.inches = inches - dd.feet * 12;       8/11
}
Passing Structures By Reference
                       Example (cont.)
     int main()
     {
        Distance d1 = { 12, 6.5 };
        Distance d2 = { 10, 5.5 };
        cout << "nd1 = "; engldisp(d1);
        cout << "nd2 = "; engldisp(d2);
        scale(d1, 0.5);
        scale(d2, 0.25);
        cout << "nd1 = "; engldisp(d1);
        cout << "nd2 = "; engldisp(d2);
        cout << endl;
        return 0;
     }
• By default, structures are passed by value (i.e. copy each member).
• Passing structure by reference is much more efficient.9/11
const Function Arguments

• Passing arguments by reference is more
  efficient and also allows the function to modify
  them directly.

• Can you pass an argument by reference for
  efficiency, but with a guarantee that the
  function cannot modify it?

• You can apply the const modifier.
                                         10/11
const Function Arguments
                          Example
#include <iostream.h>

void main()
{
  int alpha = 7;
  int beta = 11;
  aFunc(alpha, beta);
}

void aFunc(int& a, const int& b)
{
  a = 107;   // OK
  b = 111;   // error: can't modify const
}

                                            11/11

Contenu connexe

Tendances

FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3Ali Aminian
 
C++ concept of Polymorphism
C++ concept of  PolymorphismC++ concept of  Polymorphism
C++ concept of Polymorphismkiran Patel
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpprajshreemuthiah
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++NUST Stuff
 
Function in c++
Function in c++Function in c++
Function in c++Kumar
 
Bca 2nd sem u-5 files & pointers
Bca 2nd sem u-5 files & pointersBca 2nd sem u-5 files & pointers
Bca 2nd sem u-5 files & pointersRai University
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
Mca 2nd sem u-5 files & pointers
Mca 2nd  sem u-5 files & pointersMca 2nd  sem u-5 files & pointers
Mca 2nd sem u-5 files & pointersRai University
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)Ritika Sharma
 

Tendances (19)

Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
C++ concept of Polymorphism
C++ concept of  PolymorphismC++ concept of  Polymorphism
C++ concept of Polymorphism
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Function in c++
Function in c++Function in c++
Function in c++
 
Bca 2nd sem u-5 files & pointers
Bca 2nd sem u-5 files & pointersBca 2nd sem u-5 files & pointers
Bca 2nd sem u-5 files & pointers
 
Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Mca 2nd sem u-5 files & pointers
Mca 2nd  sem u-5 files & pointersMca 2nd  sem u-5 files & pointers
Mca 2nd sem u-5 files & pointers
 
Lecture 12 - Recursion
Lecture 12 - Recursion Lecture 12 - Recursion
Lecture 12 - Recursion
 
Function
FunctionFunction
Function
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 

Similaire à Lecture06

FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxDeepasCSE
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)Ameer Hamxa
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)Faizan Janjua
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxShashiShash2
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming FundamentalsZohaib Sharif
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docxJoeyDelaCruz22
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)SURBHI SAROHA
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)jewelyngrace
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping newaprilyyy
 

Similaire à Lecture06 (20)

FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptx
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
4th unit full
4th unit full4th unit full
4th unit full
 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
C++ references
C++ referencesC++ references
C++ references
 

Plus de elearning_portal (14)

Lecture05
Lecture05Lecture05
Lecture05
 
Lecture21
Lecture21Lecture21
Lecture21
 
Lecture19
Lecture19Lecture19
Lecture19
 
Lecture18
Lecture18Lecture18
Lecture18
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture16
Lecture16Lecture16
Lecture16
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture09
Lecture09Lecture09
Lecture09
 
Lecture07
Lecture07Lecture07
Lecture07
 
Lecture20
Lecture20Lecture20
Lecture20
 
Lecture03
Lecture03Lecture03
Lecture03
 
Lecture02
Lecture02Lecture02
Lecture02
 
Lecture01
Lecture01Lecture01
Lecture01
 
Lecture04
Lecture04Lecture04
Lecture04
 

Dernier

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 

Dernier (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

Lecture06

  • 1. Lecture 06 Reference Variables Learn about: - Reference arguments - Pass Arguments and Structures by reference - const function arguments Ref.: OOP using C++, Joyce Farrel, Thopson Learningv 1
  • 2. Reference Variables (page 137-139) • A reference is an alias (a different name) to a variable. • How to declare a reference variable? i) By placing a type and & in front of a variable. ii) Assign another variable of the same type to the reference variable. For example: double someMoney; double &cash = someMoney 2/11
  • 3. Reference Variables (page 137-139) double someMoney; double &cash = someMOney; cash = 6.78; cout<<cash<<endl; // displays 6.78 cout<<someMoney; // displays 6.78 someMOney = 111.333; cout<<cash<<endl; // displays 111.333 cout<<someMoney; // displays 111.333 3/11
  • 4. Reference Arguments • Passing arguments by reference allows a function to access variables in the calling program, as well as returning more than one value. • Reference arguments are indicated by the & following the data type. (float n, float &intp, float &fracp) 4/11
  • 5. Reference Arguments Example 1 #include <iostream.h> void intfrac(float n, float& intp, float& fracp) { long temp = static_cast<long>(n); // temp = 10 intp = static_cast<float>(temp); // intp = 10 fracp = n - intp; // fracp = 0.25 } void main() { float number, intpart, fracpart; do { cout << "nEnter a real number: "; cin>>number; // input: 10.25 intfrac(number, intpart, fracpart); cout << "Integer part is " << intpart << ", fraction part is " << fracpart << endl; } while( number != 0.0 ); 5/11 }
  • 6. Reference Arguments Example 1 (cont.) • The & indicates that intp is an alias for whatever variable is passed as an argument. Similarly for fracp. • Note that the & is not used in the function call. • Do not confuse with the address of operator (same symbol). 6/11
  • 7. Pass By Reference: Example 2 #include <iostream.h> void order(int& numb1, int& numb2) { if(numb1 > numb2) { int temp = numb1; numb1 = numb2; numb2 = temp; } } void main() { int n1=99, n2=11; // not ordered int n3=22, n4=88; // ordered order(n1, n2); order(n3, n4); cout << "n1=" << n1 << endl; cout << "n2=" << n2 << endl; cout << "n3=" << n3 << endl; cout << "n4=" << n4 << endl; 7/11 }
  • 8. Passing Structures By Reference Example #include <iostream.h> struct Distance { // English distance int feet; float inches; }; void engldisp( Distance dd ) { cout << dd.feet << "'-" << dd.inches << """; } void scale( Distance& dd, float factor) { float inches = (dd.feet*12 + dd.inches) * factor; dd.feet = static_cast<int>(inches / 12); dd.inches = inches - dd.feet * 12; 8/11 }
  • 9. Passing Structures By Reference Example (cont.) int main() { Distance d1 = { 12, 6.5 }; Distance d2 = { 10, 5.5 }; cout << "nd1 = "; engldisp(d1); cout << "nd2 = "; engldisp(d2); scale(d1, 0.5); scale(d2, 0.25); cout << "nd1 = "; engldisp(d1); cout << "nd2 = "; engldisp(d2); cout << endl; return 0; } • By default, structures are passed by value (i.e. copy each member). • Passing structure by reference is much more efficient.9/11
  • 10. const Function Arguments • Passing arguments by reference is more efficient and also allows the function to modify them directly. • Can you pass an argument by reference for efficiency, but with a guarantee that the function cannot modify it? • You can apply the const modifier. 10/11
  • 11. const Function Arguments Example #include <iostream.h> void main() { int alpha = 7; int beta = 11; aFunc(alpha, beta); } void aFunc(int& a, const int& b) { a = 107; // OK b = 111; // error: can't modify const } 11/11