Search code examples
oopc++11pointersvectordeque

Using vector of pointer to objects of another class


I have been trying to do the following to no avail,

In 'used.h',

#ifndef USED_H_
#define USED_H_
#include<iostream>
#include<string>
    class used
    {
    public:
      int member=0;
      used();
      virtual ~used();
    };
#endif

In the used.cc,

#include "used.h"
used::used()
{
}
used::~used()
{
}

In 'the_user.h',

#ifndef THE_USER_H_
#define THE_USER_H_
#include<queue>
#include<iostream>
    class used;      //Class forward declaring
    class the_user
    {
    public:
      std::deque<used*> my_queue;
      the_user();
      ~the_user();
    };
#endif

Now, I want to access and change 'member' in 'the_user.cc',

    #include "used.h"
    #include "the_used.h"
    #include<iostream>
    #include<queue>
    using namespace std;
    the_user::the_user()
    {
        deque <used*> my_queue;
        my_queue.resize(6);
        used* object = new used;       <-------marked line
        for(unsigned int i=0; i<my_queue.size(); i++)
        {
           my_queue.push_back(object);
        }

        cout << my_queue[5] << endl;                     //Should give 0
        my_queue[0]->member=1000;
        cout << my_queue[0]->member << endl;             //1000
    }

in main file(I have only read access),

#include "the_used.h"
#include <iostream>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main()
{
  the_used *object = new the_used();
}

Actually, I am getting undefined reference to used::used() at the marked line. What seems to be the problem? I have tried to use the same for a vector as well but to no avail. I am not allowed to make changes to the 'int main(){}'. Any help would be highly appreciated.


Solution

  • Your class declaration doesn't declare any constructor or destructor:

    class used
    {
    public:
        int member=0;
    };
    

    But in your cpp file you define them. Your compiler should complain already here:

    #include "used.h"
    used::used()
    {
    }
    
    used::~used()
    {
    }
    

    You must declare constructor and destructor in your class:

    class used
    {
    public:
        used();
        ~used();
        int member=0;
    };
    

    Then here:

    my_queue.resize(6);
    

    you will actually create 6 pointers that will be initialized to nullptr. Maybe you're aware of that, since you expect my_queue[5] to return 0.

    Then in your loop, everytime you do this:

    my_queue.push_back(object);
    

    you will increase the size of my_queue by one, thus make your loop run forever.

    Apart from that: Do. Not. Do. using namespace std;. Ever.