Return a private static member of a class

I am trying to follow this example on the net, which leads me along the following code:

EquipmentCollection.h (header file)

#ifndef EQUIMENTCOLLECTION_H_
#define EQUIMENTCOLLECTION_H_

#include "Equipment.h"
#include <vector>

class EquipmentCollection : public Equipment {
public:
    static void add( Equipment* );
    static vector<Equipment*>& get();
    ~EquipmentCollection();
private:
    static vector<Equipment*>* equipmentList;
};

#endif /* EQUIMENTCOLLECTION_H_ */

      

EquipmentCollection.cpp (source file)

#include "EquipmentCollection.h"

void EquipmentCollection::add( Equipment* equipment ) {
    if( equipmentList == NULL ) {
        equipmentList = new vector<Equipment*>();
    }

    equipmentList->push_back( equipment );
}

vector<Equipment*>& EquipmentCollection::get() {
    return *equipmentList;
}

EquipmentCollection::~EquipmentCollection() {
    delete( equipmentList );
}

      

My error is return *equipmentList;

in the original file which is giving me the error undefined reference to "EquipmentCollection::equipmentList"

. I don't know why it is giving me this error.

+3


source to share


1 answer


You haven't initialized your static member. You should add the following code to your CPP file:

vector<Equipment*>* EquipmentCollection::equipmentList = nullptr;

      

Also your code has other problems:



  • You are not instantiating EquipmentCollection

    , so your destructor will never be called and the hardware will never be freed.
  • EquipmentCollection::get

    will have undefined behavior if not previously called ::add

    , due to (8.3.2 / 4 "References"):

Note: in particular, a null reference cannot exist in a well-defined one because the only way to create such a reference would be to bind it to an "object" obtained by dereferencing a null pointer, which causes undefined behavior.

+4


source







All Articles