user1185736
user1185736

Reputation: 27

Class constructor and Arrays

I'm working on a project for school and I've hit a bit dead end. Part of the project requires us to have a class that uses an array. We must use an array (sadly we can't use vectors). I'm trying to figure out how to construct an array in the class at run time. I don't need to actually put anything in it initially, i just need to constructor to make the array a certain size. Any feed back or help is greatly appreciated. Here's what i have so far for the class and the constructor. This project is being done in c++.

#pragma once
#include <iostream>
#include <string>
using namespace std;

class Node
{

public:
    int size;
    string container[];

    Node ( int s, string c[]);
};

Node::Node (int s, string c[])
{
    size=s;
        ***I need something here that will give string container[] the size of "size"***
}

Thank you in advance.

Upvotes: 1

Views: 8930

Answers (3)

evanmcdonnal
evanmcdonnal

Reputation: 48076

I would use a pointer. When you get the size just call new with that size.

char* myArray;

constructor(int size) {
    myArray = new char[size];
}

You'll have to call delete in the destructor as well.

Upvotes: 0

Nick Banks
Nick Banks

Reputation: 4408

class Node 
{ 

public: 
    int size; 
    string* container; 

    Node ( int s, string c[]); 
    ~Node() { if (container != NULL) delete [] container; }
}; 

Node::Node (int s, string c[]) : container(NULL)
{ 
    size=s; 
    container = new string[size];
    // Copy list values into container
} 

Upvotes: -1

Luchian Grigore
Luchian Grigore

Reputation: 258558

You need a dynamically allocated array:

class Node
{

public:
    int size;
    string* container;

    Node ( int s, string c[])
    {
       container = new string[s];
       //copy c to container
    }
    ~Node ()
    {
       delete[] container;
    }
};

Also, remember to free the memory in the destructor.

Upvotes: 2

Related Questions