SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 
Function in c++
Function in c++Function in c++
Function in c++
Kumar
 

Mais procurados (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++)
 

Semelhante a Lecture06

Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
ankush_kumar
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
JoeyDelaCruz22
 
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
 

Semelhante a 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
 

Mais 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
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Último (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
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...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 

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