1

I'm just starting to learn C++ and can't figure out what I'm doing wrong.

I'm trying to build a class "Holder" that holds an array of up to 100 of another class "Obj". I have the following two classes:

class Obj {
public:
    Obj(int k, char v): key(k), val(v) {};
private:
    int key;
    char val;

   friend class Holder;
};


class Holder {
private:
    enum {MAX_SIZE = 100};
    Obj p[MAX_SIZE];
    int pSize = 0;
public:
    Holder();
    ~Holder();
//...
};

When initializing the class Holder from main(), as follows...

int main() {
    Holder test;

    return 0;
}

I'm receiving these errors after running the program:

undefined reference to "Holder::Holder()" and undefined reference to "Holder::~Holder()"

I can't tell if I'm correctly using an array as a class member variable in "Holder"? Or if I'm missing something in the constructor?

2 Answers2

0

Try this code snippet. Since constructor of Holder will require auto initialization of an Obj array, a default constructor is used :

class Obj {
public:
    Obj() :key(0),val(0){};   //Additional - default constructor
    Obj(int k, char v): key(k), val(v) {};
private:
    int key;
    char val;

   friend class Holder;
};


class Holder {
private:
    enum {MAX_SIZE = 100};
    Obj p[MAX_SIZE];
    int pSize = 0;
public:
    Holder(){}   // constructor definition 
    ~Holder(){}   // destructor definition 
//...
};

int main()
{
    Holder test;
}
seccpur
  • 4,996
  • 2
  • 13
  • 21
-1

Consider using std::array (or std::vector) and perhaps also std::pair instead of Obj.

std::array<std::pair<int, char>, 100> p;  // Will automatically init with zeroes
// Example of using it:
p[50] = std::make_pair(1234, 'a');
std::cout << "key:" << p[50].first << ", val:" << p[50].second << std::endl;
Tronic
  • 1,248
  • 12
  • 16