Cpp - References as an Alternative to Pointers for passing object to a function

Description

References as an Alternative to Pointers for passing object to a function

Demo

#include <iostream> 
   /*from  w w  w.  ja v a  2s  . c  o m*/
class Bug 
{ 
public: 
    Bug(); 
    Bug(Bug&); 
    ~Bug(); 
   
    int GetAge() const { return itsAge; } 
    void SetAge(int age) { itsAge = age; } 
   
private: 
    int itsAge; 
}; 
   
Bug::Bug() 
{ 
    std::cout << "Simple Bug Constructor ..." << std::endl; 
    itsAge = 1; 
} 
   
Bug::Bug(Bug&) 
{ 
    std::cout << "Simple Bug Copy Constructor ..." << std::endl; 
} 
   
Bug::~Bug() 
{ 
    std::cout << "Simple Bug Destructor ..." << std::endl; 
} 
   
const Bug & FunctionTwo (const Bug & theBug); 
   
int main() 
{ 
    std::cout << "Making a cat ..." << std::endl; 
    Bug bug; 
    std::cout << "bug is " << bug.GetAge()  
                 << " years old" << std::endl; 
   
    int age = 5; 
    bug.SetAge(age); 
    std::cout << "bug is " << bug.GetAge()  
                 << " years old" << std::endl; 
   
    std::cout << "Calling FunctionTwo..." << std::endl; 
    FunctionTwo(bug); 
    std::cout << "bug is " << bug.GetAge()  
                 << " years old" << std::endl; 
    return 0; 
} 
    
// functionTwo passes a ref to a const object 
const Bug & FunctionTwo (const Bug & theBug) 
{ 
    std::cout << "Function Two. Returning..." << std::endl; 
    std::cout << "now: " << theBug.GetAge() << " years old" << std::endl; 
    // theBug.SetAge(8);   const! 
    return theBug; 
}

Result

Related Topic