I have some code that includes three classes. The relevant class structure includes the following:
- class1 contains a pointer to an instance of class2
- class2 contains a private class3 class, and a function to access a reference to class 3
- class3 contains a private map class and a function to check if the map is empty
The problem I am having is when I set this up like so I get an access violation:
bool result = class1->class2->GetProperties().CheckEmpty();
But if I set it up like this I don't have any errors:
bool result = class2->GetProperties().CheckEmpty();
Why would adding another class layer suddenly cause this problem?
Here is the code I am using to reproduce the error. The two lines in the in main do not produce an error but comment those and uncomment the other two and you will get the error.
#include "stdafx.h"
#include <map>
class PropertySet
{
public:
PropertySet::PropertySet(){};
PropertySet::~PropertySet(){};
bool CheckEmpty() const { return properties.empty(); }
private:
std::map< std::string, std::string > properties;
};
class Tile
{
public:
Tile::Tile() {};
Tile::~Tile() {};
// Get a set of properties regarding the tile.
const PropertySet &GetProperties() const { return properties; }
private:
PropertySet properties;
};
class Tileset
{
public:
Tileset::Tileset(){};
Tileset::~Tileset(){};
Tile* tile;
};
int main()
{
bool test = false;
//NO error-----------------------------
Tile* t = new Tile();
test = t->GetProperties().CheckEmpty();
//-------------------------------------
//ERROR--------------------------------
//Tileset* t = new Tileset();
//test = t->tile->GetProperties().CheckEmpty();
//-------------------------------------
delete t;
return 0;
}