Cpp - Passing object by Reference for Efficiency

Description

Passing object by Reference for Efficiency

Demo

#include <iostream> 
 
class Bug //from   ww  w  .  j a v a  2s.c  o  m
{ 
public: 
    Bug();                       // constructor 
    Bug(Bug&);     // copy constructor 
    ~Bug();                      // destructor 
}; 
   
Bug::Bug() 
{ 
    std::cout << "Simple Cat Constructor ..." << std::endl; 
} 
   
Bug::Bug(Bug&) 
{ 
    std::cout << "Simple Cat Copy Constructor ..." << std::endl; 
} 
   
Bug::~Bug() 
{ 
    std::cout << "Simple Cat Destructor ..." << std::endl; 
} 
   
Bug FunctionOne(Bug theCat); 
Bug* FunctionTwo(Bug *theCat); 
   
int main() 
{ 
    std::cout << "Making a cat ..." << std::endl; 
    Bug bug; 
    std::cout << "Calling FunctionOne ..." << std::endl; 
    FunctionOne(bug); 
    std::cout << "Calling FunctionTwo ..." << std::endl; 
    FunctionTwo(&bug); 
    return 0; 
} 
   
// FunctionOne, passes by value 
Bug FunctionOne(Bug theCat) 
{ 
    std::cout << "Function One. Returning ..." << std::endl; 
    return theCat; 
} 
   
// functionTwo, passes by reference 
Bug* FunctionTwo (Bug *theCat) 
{ 
    std::cout << "Function Two. Returning ..." << std::endl; 
    return theCat;  
}

Result

Related Topic