Let's say I want a private pointer to a map in my class. And I want it to be pointing to NULL if the argument of my constructor (a boolean) is true. Is it the correct way of doing it ? (if my boolean is false, I add a first element in my map)
using namespace std;
#include <map>
class Class {
public:
Class(bool a)
: _myMap(0) {
if (a) {
_myMap = new map<int, bool>(); // initialized to NULL
} else {
(*_myMap)[0] = true; // added a first key-value to map
}
}
~Class() {
delete _myMap;
}
private:
map<int, bool>* _myMap;
}
EDIT Here is how I fixed my problem :
using namespace std;
#include <map>
class Class {
public:
Class(bool a)
: _myMap(0) { // map initialized to NULL
if (a) {
_myMap = new map<int, bool>();
}
}
~Class() {
delete _myMap;
}
void addValue(bool b, int i) {
if (_myMap != 0) {
(*_myMap)[i] = b;
}
}
private:
map<int, bool>* _myMap;
}
To answer folks that ask me why I needed a pointer to a map instead of a simple map : when I use my component Class, I don't want to add values if a (used in the constructor) is false, i.e if my map is pointing to NULL.