I am unable to use add values this map defined in header file as protected attribute from class member function.
class xyz{
protected:
map < string, string > *tagsMap;
public:
xyz();
//set Tags
void addTag(string _tagName, string _tagValue) const;
}
// In cpp class,
//set new Tags
void xyz::addTag(string _tagName, string _tagValue) const {
//map < string, string > tagsMap ;
//gives error until I uncomment above line, but thats local map
tagsMap.insert(pair<string, string>(_tagName, _tagValue));
// first insert function version (single parameter):
tagsMap .insert(pair<string, string>(_tagName, _tagValue));
for (auto& t : tagsMap )
cout << "addTag():" << t.first << "=" << t.second << endl;
}
2 Answers 2
You have 3 problems:
1) Class member is declared a pointer
The commented line inside addTag()
:
// map < string, string > tagsMap;
It is not a pointer, which is the reason why it works if you uncomment the local map declaration.
However, this is not correct logically since it's not a member of your class - it shadows your tagsMap
class member.
Thus, you need to declare tagsMap
in your xyz
class a non-pointer.
map < string, string > *tagsMap;
// ^ remove asterisk '*'
2) Missing Semicolon after class definition
Add ;
semicolon, after your class definition
class xyz {
...
}
// ^^^ add semicolon here
3) Const function
Remove const
in addTag()
to be able to write on tagsMap
class member
void xyz::addTag(string _tagName, string _tagValue) const { .. }
// ^^^^^ remove const
void addTag(string _tagName, string _tagValue) const;
// ^^^^^ remove const
1 Comment
Yes pointer was not needed. It worked after making the function non-const as suggested by @codekaizer in comments above.
class xyz{
protected:
map < string, string > tagsMap;
public:
xyz();
//set Tags
void addTag(string _tagName, string _tagValue);
}
// In cpp class,
void xyz::addTag(string _tagName, string _tagValue) {
tagsMap.insert(pair<string, string>(_tagName, _tagValue));
}
;
after your class def