ArcheAngel ArcheAngel - 2 months ago 9
C++ Question

How do I initialize a dynamically allocated array within a class constructor

we are supposed to assign an empty string into each index and later replace
that with a value in the function addB().
I am quite new to this so I am having a lot of trouble.

class A //in a.h

{

private:

B * b;

int maxNumberOfItems;

//...

public:

A();

~A();

void addB(const B & something);

};

//in a.cpp

A::A()

{

maxNumberOfItems=10;
for(int i=0;i<maxNumberOfItems;i++)
{
b[i]="";//has to be an empty string, I am getting a segmentation fault
}

}

A::~A(){/*...*/}

//...

//in b.h

class B
{

private:

string name;

int price;

public:

void setName(string);

string getName();

void setPrice();

int getPrice(int);

B & operator=(string &);

};

//in b.cpp

B & B::operator=(string & a){name = a;price = 0; return *this;}
//...


this is only a snippet of the program showing my issue

Answer

You should allocate memory before using dynamic array.I have allocated memory for b

class A //in a.h

{

private:

    B * b;

    int maxNumberOfItems;

    //...

public:

A();

~A();

void addB(const B & something);

};

//in a.cpp

A::A()

{
    maxNumberOfItems=10;
    b = new B[maxNumberOfItems];

    for(int i=0;i<maxNumberOfItems;i++)
    {
    b[i]="";//has to be an empty string, I am getting a segmentation fault
    }

}

A::~A(){/*...*/}

//...

//in b.h

class B
{

private:

    string name;

    int price;

public:

    void setName(string);

    string getName();

    void setPrice();

    int getPrice(int);

    B & operator=(string &);

};

//in b.cpp

B & B::operator=(string & a){name = a;price = 0; return *this;}