Dynamic memory for class array

Having trouble figuring out how to allocate memory for a class array in C++.

Look for the *****. This indicates the line I can't get to work. I included class definitions and the Entry class implementation so you could get a better picture of what things look like. My code is as follows:

class Entry
{
public :

Entry( string word, string def );
~Entry();

string getDefinition( const string &word );

private :

// the privates are up to you
string m_word;
string m_def;
};

Entry::Entry( string word, string def )
{
Entry::m_word = word;
Entry::m_def = def;
}

class Dictionary
{
public :

typedef void (*WordDefFunc)(const string &word, const string &definition);

Dictionary( const string &filename );
~Dictionary();

string lookupDefinition( const string &word );

void forEach( WordDefFunc func, bool forward );

private :
Entry *m_dictionary;
int m_numEntries;
};


Dictionary::Dictionary( const string &filename )
{
char buffer[BUFFER_SZ];
char text[INPUT_LINE_MAX_LEN]; // Buffer for each line read in from file
string word;
string def;

ifstream input (filename, ios::in); // Open file for reading
if (input.is_open()) // If the file opened properly perform the following
{
input.getline( text, INPUT_LINE_MAX_LEN);
m_numEntries = atoi(text);
***** m_dictionary = new Entry[m_numEntries](0, 0);

> how to allocate memory for a class array in C++.

let std::vector<> do that for you.
http://www.mochima.com/tutorials/vectors.html
Forgot to mention that this is for a C++ class. We haven't learned vectors yet and are suppose to do it the hard way.
Define a default constructor for the class Entry:

1
2
3
4
5
6
7
8
9
class Entry
{
    public :

        // this also acts as a default constructor
        explicit Entry( string word = "" , string def = "" ); 

        // ...
};


And then, to create the array: /* Entry* */ m_dictionary = new Entry[m_numEntries] ;

To set a value: m_dictionary[3] = Entry( "abcd", "efgh" ) ;

Finally to destroy the array (in the destructor): delete[] m_dictionary ;
Awesome! Thank you. So far this is working. I still have to do my loop for setting the values, but looks like this sends me on the right track.
Topic archived. No new replies allowed.