CPP Class Members as pointers

How to handle members as pointers.

  • Sometime you need to have dynamic allocation of members of a class.
  • In those cases is it important to remove allocated space for members in the destructor of the object.
    Here is an Example
    #include <iostream>
    using namespace std;
    class Person {
    public:
    // constructor
      Person(int age, int weight);
    // destructor
      ~Person();
      int getAge(){ return *pAge;}
      int getWeight(){ return *pWeight;}
    
    private:
      int * pAge;
      int * pWeight;
    
    };
    Person::Person(int age, int weight) {
    // Allocate a location on the free store for the age in the Constructor
       pAge = new int(age);
    // Allocate a location on the free store for the weight in the Constructor       
       pWeight = new int(weight);
    }
    Person::~Person() {
    // Deallocate the location on the free store for the age in the Destructor
       if (pAge!=0)
         delete pAge;
    // Deallocate the location on the free store for the weight in the Destructor
       if (pWeight!=0)
         delete pWeight;
    }
    
    int main(){ 
    	Person * pPers=new Person(34,56);
    	cout << "Personal data:\nAge=" << pPers->getAge()<< "\n";  
    	cout << "Weight=" << pPers->getWeight()<< "\n";  
    }
    When we run this application the result will be:
    Personal data:
    Age=34
    Weight=56

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.