flaviumanica
flaviumanica

Reputation: 195

Using destructor in class

I've got a project in C++ that uses classes(quite basic elements). My class looks like this:

class vehicule: public frane,public motor,public directie,public noxe,public caroserie
{
    char tip[40];
    int placfatacant,placfatatot;
    static const int placfatapret=18;
    int placspatecant,placspatetot;
    static const int placspatepret=15;
public:
    vehicule()
    void settip(char)
    void verifauto()
;};

I've been told I have to use copy constructor and destructor. I have some examples,but both use dynamic allocation. Now my question is:what should my copy constructor/destructor do as I don't have dynamic allocated memory to copy/delete? Or should I declare the data as

int *placfatacant

and then use

delete placfatacant

? Thanks in advance!

Upvotes: 2

Views: 152

Answers (2)

AMDG
AMDG

Reputation: 975

If it is for school purpose you can change :

// From:
char tip[40];

// To:
char * tip;`

And then in your constructor you will make:

tip = new char[40]();

Now you have to create a copy constructor like this one:

vehicule(const vehicule & toCopy)
{
    tip = new char[40]();
    strcpy(tip, toCopy.tip);
}

Your destructor just need to deallocate tip:

~vehicule()
{
    delete tip;
}

Upvotes: 2

Lawrence Aiello
Lawrence Aiello

Reputation: 4658

You only need to declare a constructor if you need to handle the deletion of dynamically allocated variables, as you said. In general, for every new, there must be a delete.

I don't see any new'd objects in your class, so I would just let the compiler-generated destructor/copy constructor do its thing. Your class is entirely statically allocated and will be deleted when it falls out of scope of the context in which it is used.

Upvotes: 3

Related Questions