I encountered a scenario recently whilst working with a student, and I'm struggling to understand why the following example is failing.
I have a pointer to an object Game, and Game itself has a pointer to vector<Pair>. The failing line is the last line of of main(), where I am daisy-chaining methods:
gamePointer->getPairs()->push_back(pair);
In the above line, getPairs() returns a vector<Pair>*, and then push_back() is called to add a new Pair to the vector. This results in a read access violation. Interesting, swapping out the Game's vector<Pair> with a string, say, allows me to write the following, and it works:
gamePointer->getPairs()->append("B");
I've simplified the problem and reproduced a full example:
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Pair
{
private:
string previous;
string next;
public:
Pair();
Pair(string previous, string next);
string getPrevious();
string getNext();
void setPrevious(string previous);
void setNext(string next);
};
class Game
{
private:
vector<Pair>* pairs;
public:
Game();
vector<Pair>* getPairs();
void setPairs(vector<Pair>* pairs);
};
Pair::Pair()
{
this->setPrevious("a");
this->setNext("b");
}
Pair::Pair(string previous, string next)
{
this->setPrevious(previous);
this->setNext(next);
}
string Pair::getPrevious()
{
return this->previous;
}
string Pair::getNext()
{
return this->next;
}
void Pair::setPrevious(string previous)
{
this->previous = previous;
}
void Pair::setNext(string next)
{
this->next = next;
}
Game::Game()
{
vector<Pair> pairs;
pairs.reserve(10);
this->setPairs(&pairs);
}
vector<Pair>* Game::getPairs()
{
return this->pairs;
}
void Game::setPairs(vector<Pair>* pairs)
{
this->pairs = pairs;
}
int main()
{
Game game;
Game* gamePointer = &game;
Pair pair("Previous", "Next");
gamePointer->getPairs()->push_back(pair);
}