Search code examples
c++classvectorstaticmember

How to access class elements from static vector?


I have a static vector of class Town inside the same class, and I am trying to access it's elements.

Code:

// town.h
class Town
{
    public:
        static int nrOfTowns;
        static std::vector<Town> *towns;
        std::string name;
};

int Town::nrOfTowns = 0;
std::vector<Town> *Town::towns = NULL;

// main.cpp
/* code */
Town::towns = new std::vector<Town> (Town::nrOfTowns); // initializing vector
Town::towns[0].name; // gives me an error

I'm getting an error: class std::vector<Town> has no member named name.


Solution

  • In your code towns is a pointer to a vector but probably it should be a vector:

    // town.h
    class Town
    {
        public:
            static int nrOfTowns;
            static std::vector<Town> towns;
            std::string name;
    };
    
    int Town::nrOfTowns = 0;
    std::vector<Town> Town::towns;
    
    // main.cpp
    /* code */
    Town::towns.resize(Town::nrOfTowns);
    Town::towns[0].name;
    

    If you really want it to be a pointer you have to dereference the pointer

    // town.h
    class Town
    {
        public:
            static int nrOfTowns;
            static std::vector<Town> *towns;
            std::string name;
    };
    
    int Town::nrOfTowns = 0;
    std::vector<Town> *Town::towns = nullptr;
    
    // main.cpp
    /* code */
    Town::towns = new std::vector<Town> (Town::nrOfTowns); // initializing vector
    (*Town::towns)[0].name; // gives me an error
    delete Town::towns;