0

I have class Walls in my program. Inside of class are objects Wall1, Wall2 etc. I want to do something like this: class definition:

class Walls {
    
public:
    Walls(){
        nPositionX = nMapWidth - 1;
        nHoleSize = 1;
        nHolePosition = rand()%(nMapHeight - nHoleSize);
        count++;
    }
    static int getCount() {
        return count;
    }
    int getPositionX()
    {
        return nPositionX;
    }
    
    
private:
    int nPositionX;
    int nHolePosition;
    int nHoleSize;
    static int count;
};

access to object

for (int i = 0; i < Walls::getCount(); i++) {
    
    int nPosx = Wall"i".getPositionX();
    
}
}

Is that possible in c++? Ok big thanks for everyone for help. I don't know why I didn't tried it before.

8
  • 5
    You can't. Learn about arrays. Commented Nov 17, 2020 at 16:56
  • 3
    No, but you can use std::vector to maintain a collection. Commented Nov 17, 2020 at 16:57
  • 1
    Or a std::map using name strings as keys, ie: std::map<std::string, Wall> walls; ... int nPosx = walls["Wall" + std::to_string(i)].getPositionX(); Commented Nov 17, 2020 at 17:00
  • Show us the definition of Walls. Commented Nov 17, 2020 at 17:00
  • @user253751 and cigien ok ;/ thank U Commented Nov 17, 2020 at 17:01

2 Answers 2

1

You can use an array or std::vector for that, eg:

std::array<Wall, MAX_WALLS> m_walls;
or
std::vector<Wall> m_walls;

...

// initialize m_walls[0], m_walls[1], etc as needed...

...

for (size_t i = 0; i < m_walls.size(); i++) {
    int nPosx = m_walls[i].getPositionX();
    ...
}

Or, you can use a std::map, eg:

std::map<std::string, Wall> m_walls;

...

// initialize m_walls["Wall1"], m_walls["Wall2"], etc as needed...

...

for (int i = 1; i <= getCount(); i++) {
    int nPosx = m_walls["Wall" + std::to_string(i)].getPositionX();
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

The code is not executed until you execute your program, but in the executable there are no variable names anymore. Hence, no.

You can use an array or vector:

struct Wall { int get_position() const { return 42; } };
using Walls = std::vector<Wall>;

Walls walls;
for (const auto& wall : walls) {
    int nPosx = wall.get_position();
}

Or if you really want to map names to objects, use a std::map:

std::map<std::string,Wall> named_walls;

named_walls["stone wall"] = Wall();

Comments

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.