Search code examples
c++static-membersprivate-members

Return private static member of a class


I'm trying to follow this example on the net that leads me on 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; on the source file which gives me undefined reference to "EquipmentCollection::equipmentList" error. I don't know why it gives me that error.


Solution

  • You have not initialized your static member. You should add in your CPP file, the following code:

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

    Also your code has other problems:

    • You don't create any instance of EquipmentCollection, so your destructor will never be called and equipment will never be freed.
    • EquipmentCollection::get will have an undefined behavior if no ::add was called before, because of (8.3.2/4 "References"):

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