2

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?

9
  • You are showing the declarations of your constructor and destructor for Holder but where are the definitions? Commented Mar 27, 2018 at 4:53
  • where is the constuctor for Holder? Commented Mar 27, 2018 at 4:53
  • Is your constructor actually implemented/defined? Commented Mar 27, 2018 at 4:54
  • Is it your wish that the compiler will generate the c'tor and d'tor for Holder? Commented Mar 27, 2018 at 4:55
  • similar question: stackoverflow.com/questions/15712821/… Commented Mar 27, 2018 at 4:57

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Removing the user defined constructor and destructor would be a better idea. That at least lets the user zero-initialize using value initialization.
Also the error has nothing to do with the data members.
This got rid of the error! Thanks a lot for your reply, seccpur!
-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;

1 Comment

Someone downvoted -- maybe you could also comment why this is not good?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.