Cpp - Free data members of a class using destructor

Introduction

The following code shows how to free up memory allocated in the class constructor via its destructor

Demo

#include <iostream> 
 
class Employee /*from   w ww.  ja v a2s . c o  m*/
{ 
public: 
    Employee(); 
    ~Employee(); 
    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; 
}; 
 
Employee::Employee() 
{ 
    itsAge = new int(2); 
    itsWeight = new int(5); 
} 
 
Employee::~Employee() 
{ 
    delete itsAge; 
    delete itsWeight; 
} 
 
int main() 
{ 
    Employee *emp = new Employee; 
    std::cout << "emp is " << emp->GetAge()  
                   << " years old" << std::endl; 
 
    emp->SetAge(5); 
    std::cout << "emp is " << emp->GetAge()  
                   << " years old" << std::endl; 
 
    delete emp; 
    return 0; 
}

Result

Related Topic