Returning a Reference to an Object on the Heap - C++ Data Type

C++ examples for Data Type:Reference

Description

Returning a Reference to an Object on the Heap

Demo Code

                                                  
#include <iostream> 
                                                     
class SimpleCat //ww  w .  j av a2  s  .  c o m
{ 
public: 
    SimpleCat (int age, int weight); 
    ~SimpleCat() {} 
    int GetAge() { return itsAge; } 
    int GetWeight() { return itsWeight; } 
                                                     
private: 
    int itsAge; 
    int itsWeight; 
}; 
                                                     
SimpleCat::SimpleCat(int age, int weight): 
itsAge(age), itsWeight(weight) {} 
                                                     
SimpleCat & TheFunction(); 
                                                     
int main() 
{ 
    SimpleCat &rCat = TheFunction(); 
    int age = rCat.GetAge(); 
    std::cout << "rCat is " << age << " years old!" << std::endl; 
    std::cout << "&rCat: " << &rCat << std::endl; 
    // How do you get rid of that memory? 
    SimpleCat *pCat = &rCat; 
    delete pCat; 
    // Uh oh, rCat now refers to ?? 
    return 0; 
} 
                                                     
SimpleCat &TheFunction() 
{ 
    SimpleCat *pFrisky = new SimpleCat(5,9); 
    std::cout << "pFrisky: " << pFrisky << std::endl; 
    return *pFrisky; 
}

Result


Related Tutorials