Member Data on the Heap - C++ Operator

C++ examples for Operator:new

Introduction

The data members of a class can be a pointer to an object on the heap.

Demo Code

                                          
#include <iostream> 
                                          
class SimpleCat { 
public: // w  ww  .  jav a2 s . c o  m
    SimpleCat(); 
    ~SimpleCat(); 
    int GetAge() const { return *itsAge; } 
    void SetAge(int age) { *itsAge = age; } 
                                          
    int GetWeight() const { return *itsWeight; } 
    void setWeight (int weight) { *itsWeight = weight; } 
                                          
private: 
    int *itsAge; 
    int *itsWeight; 
}; 
                                          
SimpleCat::SimpleCat() 
{ 
    itsAge = new int(2); 
    itsWeight = new int(5); 
} 
                                          
SimpleCat::~SimpleCat() 
{ 
    delete itsAge; 
    delete itsWeight; 
} 
                                          
int main() 
{ 
    SimpleCat *Frisky = new SimpleCat; 
    std::cout << "Frisky is " << Frisky->GetAge()  << " years old" << std::endl; 
                                          
    Frisky->SetAge(5); 
    std::cout << "Frisky is " << Frisky->GetAge()  << " years old" << std::endl; 
                                          
    delete Frisky; 
    return 0; 
}

Result


Related Tutorials