I am new to C++ programming. I am trying to implement a Command design pattern using a vector of pointers to some Command instances.
I can iterate over the vector using another aproach (for example using the index to access every element) but I would like to understand why I get the error.
I asume that vector allocates every element contiguously and that every element has the same size.
struct Command {
virtual void execute(){};
};
struct CommandOne : Command {
std::string member = "string";
void execute() override{
std::cout << member << std::endl;
}
};
struct CommandTwo : Command {
void execute() override {
std::cout << "string" << std::endl;
}
};
CommandOne commandOne{};
CommandTwo commandTwo{};
std::vector<Command*> commands;
int main (int argc, char** argv){
commands.push_back(&commandOne);
commands.push_back(&commandTwo);
Command* ptr_commands = commands.at(0);
ptr_commands->execute();
ptr_commands++;
ptr_commands->execute();
return 0;
}
The expected output would be:
string
string
But I get:
string
segment fault