Say I have a class named Contestant, could I declare an instance of the Contestant class as:

Contestant *c = new Contestant;

Well the Contestant class contains strings of first name, last name, age, and country. At run time the user passes a input file with various commands and the info that Contestant class is supposed to hold. So I have no idea how long these strings might be.

That shouldn't matter. As long as your declare your your strings using the type "string", you will be able to store a string of any length for your string values.

This is completely independent from your declaration of a Contestant object.

yes you can. But remember to deallocate the memory when it is no longer needed to prevent memory leak.

Normally I would do something like this for dynamic allocation:

Contestant* C = NULL;
C = new Contestant;
if(C)  // test valid allocation
{
// do whatever you want here


// Memory deallocation
delete C;
C = NULL;
}

Hi,
keep also in mind that whenever u allocate (using the -new- operator) an object which has a constructor, AN INITIALIZATION is mandatory.

This is simple when u haven't defined any constructor, since then the default constructor is called. On the other hand if u defined only e.g. a 2-argument constructor u cannot use the expression u wrote at the beginning of the post, unless u define a no-argument constructor.

He could always use:

Contestant *c = new Contestant(arg1, arg2);

BOTTOM LINE IS:
Don't allocate dynamically unless you need to.
And you need to do it if you don't know (for example) number of contestors.
But even then, you could make a vector<Contestant> to store all of them

Normally I would do something like this for dynamic allocation:

Contestant* C = NULL;
C = new Contestant;
if(C)  // test valid allocation
{
// do whatever you want here


// Memory deallocation
delete C;
C = NULL;
}

Your approach will not work: operator new does not yield a NULL pointer on failure - it throws an exception. The "if (C)" test in your code therefore cannot yield false.

This article has been dead for over six months. Start a new discussion instead.