Class 1:
class Class1{
public:
Class1(Class2 * a, int b );
~Class1();
friend ostream& operator<< (ostream& x, const Class1& c1);
private:
int b;
Class2 * a;
};
ostream& operator<< (ostream& x, const Class1& c1)
{
stream<<"("<<c1.a->label<<","<<c1.b<<")"<<endl;
return x;
}
Class2 (In another file):
class Class2
{
public :
Class2 (string label);
~Class2();
string getLabel()
{
return label;
}
private:
string label;
vector<Class1 *> c1vector;
};
Question:
I'm trying to print the label and b of an edge, but it says the label is private. Can you tell me what I'm doing wrong? Thanks.
Well, you are trying to access a private member of Class2 directly, and the private property is actually what prevents you from doing this. (And the fact that you qualified operator<< friend in Class1 doesn't change anything, label is a private member of Class2).
Either make the member public (not recommended) or provide a public member function that returns the value of this member.
You have to write in Class2 friend ostream& operator<< (ostream& x, const Class1& c1);, because only Class 1 is its friends but label if a private attibute of class2
label is private within Class2 so it cannot be access through Class or your operator<< insertion function. The simplest solution is to provide a public const get_label function in Class2 to access the label string.
A more in depth approach is to give Class2 its own print mechanism (either through a print/display/show function, or with its own operator<< that can be used to show the label.
One issue is that: label is private in Class2, you cannot directly access it inside Class1 via an instance of Class2, which is a in this case. You may need to provide getters inside Class2.
class Class2
{
public :
string getLable()
{
return label;
}
private:
string label;
};//^^other members skipped for clearance purpose
Related
I'm having two classes, PlayerCharacter and Ability. The Ability class has an pure virtual function which I declare as a friend to PlayerCharacter. However, I seem to be unable to access the private members within the friend declared function. Is it something I overlook?
I have attemped to declare the child function rather than the virtual one as the friend function, but to no effect.
player_chracter.h :
#include "ability.h"
class PlayerCharacter : public Character {
private:
// Friend function
friend bool Ability::ExecuteAbility(PlayerCharacter& in_player);
// This doesn't work either
//friend bool Dash::ExecuteAbility(PlayerCharacter& in_player);
// Private variable
float top_speed_;
}
ability.h :
//Forward declaration
class PlayerCharacter;
class Ability {
public:
Ability();
~Ability();
virtual bool ExecuteAbility(PlayerCharacter& in_player) = 0;
};
//---------------------------------------------------------
class Dash : public Ability {
public:
Dash();
~Dash();
bool ExecuteAbility(PlayerCharacter& in_player);
};
ability.cpp :
#include "ability.h"
#include "player_character.h" //Follow through on forward declaraction
bool Dash::ExecuteAbility(PlayerCharacter& in_player) {
float example = in_player.top_speed_;
}
In the code above, why cannot I access top_speed_ and put it in the float example variable?
As per [class.friend]/10, friendship is not inherited.
A derived class does not automatically become a friend of a class just because its parent class is a friend of that class.
The reason why the below also does not work either is probably because Dash is not defined before the function ExecuteAbility is defined.
friend bool Dash::ExecuteAbility(PlayerCharacter& in_player);
However, with the proper order of definitions it will work. See DEMO.
From cppreference:
Friendship is not transitive (a friend of your friend is not your friend)
Friendship is not inherited (your friend's children are not your friends)
Even if Dash::ExecuteAbility overrides a friend function from its base class, it does not benefit from it. You'll have to rethink your design.
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;
}
consider the following example.
class A
{
int member;
};
class B
{
A& a_ref;
void manipulate()
{
a_ref.member++;
}
};
Now, obviously, B::manipulate can not access a_ref. I would like to allow (only) class B to get (reference) to A::member. I know that there exists friend keyword, but I do not know how to use it properly. My intention is, that I could change B::manipulate implementation to become this
int& A::only_B_can_call_this() // become friend of B somehow
{
return member;
}
void B::manipulate()
{
a_ref.only_B_can_call_this()++;
}
To make B a friend:
class A
{
int member;
friend /*class*/ B; // class is optional, required if B isn't declared yet
};
Note that friends are anti-patterns - if something is private, it probably shouldn't be accessed. What are you trying to accomplish? Why isn't A self-contained? Why does another class need to access its internal data?
Use friend if you have valid answers/reasons for these questions.
You simply add friend class <class_name>; to the class that wants to make its members accessible, where <class_name> is the name of the class that you want to provide access for.
class A
{
friend class B; // allow class B to access private members of A
int member;
};
class B
{
A& a_ref;
void manipulate()
{
a_ref.member++;
}
};
I encountered this problem when implementing a class:
class Cell {
bool isAlive;
int numNeighbours;
//...omit irrelavent private members
public:
Cell(); // Default constructor
~Cell(); // Destructor
void setLiving();
....
};
void Cell::setLiving(){
isAlive=true;
}
class Grid{...
friend std::ostream& ::operator(std::ostream& out, const Grid &g);
};//...omit
std::ostream& ::operator<<(std::ostream &out, const Grid &g){
int i,j;
for(i=0;i<g.gridSize;i++){
for(j=0;j<g.gridSize;j++){
if(**g.theGrid[i][j].isAliv*e*) out<<"X";
else out<<"_";
}
out<<endl;
}
return out;
}
The complier said that "isAlive" is a private member so I can't call it that way
I think the problem is at "g.theGrid[i][j].isAlive"
I tried to friend class Grid but it didnt help
You mentioned operator<< — it's most likely a free function, so it needs to be declared as friend to be able to access private members.
class Cell {
friend std::ostream& operator<<(std::ostream&, const Grid&);
// ...
};
The class member isAlive is private, so the operator didn't have the right to access it, you need to put a friend declaration in the body of Cell's definition.
class Cell {
friend std::ostream& operator<<(std::ostream&, const Cell&);
// ...
};
This line
if(**g.theGrid[i][j].isAlive) out<<"X"
Is accessing the private member 'isAlive'. I assume theGrid is a two dimensional array of Cell objects. You need a getLiving() method defined. Then use it here.
isAlive is private, declare it as public...
EDIT1:
class Cell {
public:
bool isAlive;
Update:
private members of a class are accessible only from within other members of the same class or from their friends.
protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.
Finally, public members are accessible from anywhere where the object is visible.
When defining a class as a friend class, does it matter in which accessor section the definitions is placed, and if so does that change the members the friend has access to?
class aclass
{
private:
// friend bclass;
public:
// friend bclass;
protected:
// friend bclass;
};
class bclass
{};
Access specifiers do not apply to friend function/Class
You can declare the Friend Function or Class under any Access Specifier and the Function/Class will still have access to all the member variables(Public,Protected & Private) of that Class.
Once you place friend class/function inside a given class (say 'aclass') anywhere. It will have access to all defined members of the class (irrespective of public/private/protected); for example:
class aClass
{
public: int pub; void fun1() {}
protected: int pro; void fun2() {}
private: int pri; aClass(const aClass& o);
friend void outsider ();
};
Friend function outsider() can access pub, pro, pri, fun1, fun2; but not aClass copy constructor in this case (if it's not defined anywhere).
Friend functions aren't placed inside any accessors by convention, because by definition they aren't part of the class. You might do something like this:
class Elephants
{
//friend void notAMemberFuncion(argument 123);
public:
// member functions;
protected:
// data members;
};
The friend class/function can access all the private/protected/public members of class, which access section the friend class/function is placed doesn't make any difference.
It's suggested to put friend class/function in the public section, because friends is part of the class interface.