Problem with pointer array

I am writing two classes named 'Set' and 'Element' and I want to write a method that makes Set store an object of Element.

Here is my code:

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include "Set.h"

using namespace std;

int main()
{
    Set se(10);
    cout<<"Set created"<<endl;
    Element el("one","two", 3.0);
    cout<<"Element created"<<endl;
    se.addItem(el);

    return 0;
}


Set.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef SET_H
#define SET_H
#include "Element.h"

class Set
{
private:
        int maxItems;
        int numItems;
        Element *Setp;

public:
        Set(int items = 100);
        void addItem(Element item);
        ~Set();
};

#endif 


Set.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "Set.h"

Set::Set(int items)
{
    maxItems = items;
    numItems = 0;
    Element *Setp = new Element[20];
}

Set::~Set()
{
    delete[] Setp;
}

void Set::addItem(Element item)
{

    if(numItems < maxItems)
    {
        cout<<item.getNa()<<" is getting added to Set"<<endl;
        Setp[numItems]= item;
        numItems++;
        cout<<"Added";
    }

}


Element.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#include <iostream>
#include <string>
#ifndef ELEMENT_H
#define ELEMENT_H


using namespace std;

class Element
{
private:
        string co; 
        string na; 
        double pr; 

public:
        Element(string mc = "", string mn = "", double mp = 0);
        string getCo();
        string getNa();
        double getPr();

};


Element.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "Element.h"

Element::Element(string mc, string mn, double mp)
{
    co = mc;
    na = mn;
    pr = mp;
}

string Element::getCo()
{
    return co;
}

string Element::getNa()
{
    return na;
}

double Element::getPr()
{
    return pr;
}


My program always ends up crashing, the problem is definitely with this line in addItem:
Setp[numItems]= item;
If I try to do this *Setp[numItems]= item; the program does not compile.

How can I make my addItem method work?
This was a good one and I see this all the time in the industry.

In line of code 7 of Set.cpp, you declared Element * Setp. What it will happen is it will allocate 20 Element objects and assign to the local Setp variable. That is, the Set::Setp variable is never set since you declared a local one.

All you need to do is remove Element * and you're good to go :-)
Thank you very much! I spent many days trying to figure this out.
Topic archived. No new replies allowed.