Search code examples
c++dynamic-memory-allocation

Constructors for C++ objects


I have class Person as following :

class Person {   
    char* name;
    int age;
};

Now I need to add two contructors. One taking no arguments, that inserts field values to dynamically allocated resources. Second taking (char*, int) arguments initialized by initialization list. Last part is to define a destructor showing information about destroying objects and deallocating dynamically allocated resources. How to perform this task ?

That's what I already have :

class Person {   
    char* name;
    int age;
public:
    Person(){
        this->name = new *char;
        this->age = new int;
    }

    Person(char* c, int i){
    }
};

Solution

  • In the default constructor, allocation of the char array should include its desired size, e.g.

    this->name = new char[32];
    

    Note that this size includes the terminating 0 character, so the effective length of names you can store in this array is 31.

    In the parameterized constructor, you can simply assign the given parameters to your class members.

    In the destructor, you need to deallocate dynamically allocated resources - make sure to use delete[] when, and only when, deallocating memory allocated with new[]:

    ~Person(){
        std::cout << "Destroying resources" << std::endl;
        delete[] name;
        delete age;
    }
    

    Update: I missed this one: if you want to allocate age dynamically, you should declare it as int* age.

    I assume that the point of this exercise is to practice dynamic allocation/deallocation; in this context, it is fine. However, in general, it is not good practice to dynamically allocate ints, and instead of char* you should almost always use std::string, which handles memory allocation for you automatically and safely.