I have 2 classes (firstClass and secondClass) which firstClass is a friend of secondClass, and has a private nested unordered_map, which I want to access it in a function of secondClass. So basically the code is like this:
class secondClass;
typedef unordered_map STable<unsigned, unordered_map<unsigned, double> > NESTED_MAP;
class firstClass{
friend class secondClass;
void myfunc1(secondClass* sc){
sc->myfunc2(&STable);
}
private:
NESTED_MAP STable;
};
class secondClass{
public:
void myfunc2(NESTED_MAP* st){
//Here I want to insert some elements in STable.
//Something like:
st[1][2]=0.5;
}
};
int main(){
firstClass fco;
secondClass sco;
fco.myfunc1(&sco);
return 0;
}
I know that it should be trivial, but I don't know how to solve it. Any idea? (I changed the code and the question to make it more clear)
A friend class is allowed to access any private member, so you can simply invoke methods and modify properties as you would do if they had been public.
Here the documentation, it says:
The friend declaration appears in a class body and grants a function or another class access to private and protected members of the class where the friend declaration appears.
That said, by looking at your example, I'd rather change the place where to put the friend keyword, for it looks to me that myfunc2 ought not to be public.
It follows an example where I applied the above suggestion and that shows how to deal with private members from a friend class:
#include<unordered_map>
using namespace std;
class firstClass;
class secondClass{
friend class firstClass;
private:
void myfunc2(unordered_map<unsigned,double>& map){
map[1]=0.5;
}
};
class firstClass{
public:
void myfunc1(secondClass* sc){
// here firstClass is accessing a private member
// of secondClass, for it's allowed to do that
// being a friend
sc->myfunc2(STable);
}
private:
unordered_map<unsigned,double> STable;
};
int main(){
firstClass fco;
secondClass sco;
fco.myfunc1(&sco);
return 0;
}