This is part of a larger project.
Basically I have a class “X” to manage the program and that class has an array of pointers to objects from a class “Y” and there are another class “Z” where I need to access the objects of the class “Y”, for example a print.
I am getting the error “was not declared on this scope”
I tried to make the class “Z” friend of the class “Y” but it’s not working.
I wrote code to demonstrate this problem:
#include <iostream>
using namespace std;
class BaseClass;
class OtherClass;
class Manager;
class BaseClass
{
friend class OtherClass;
public:
BaseClass(){}
void setNum(int num){_num = num;}
int getNum(){return _num;}
private:
int _num;
};
class OtherClass
{
public:
OtherClass(){}
void print(){
cout << _bc[0]->getNum() << " " << _bc[1]->getNum() << endl;
}
};
class Manager
{
friend class OtherClass;
public:
Manager(){}
void run(){
_bc = new BaseClass*[10];
_bc[0]->setNum(20);
_bc[1]->setNum(30);
_oc.print();
}
private:
BaseClass ** _bc;
OtherClass _oc;
};
int main()
{
Manager m;
m.run();
return 0;
}
Maybe this is very simple but it’s late here, i’m sleepy and I want to solve this problem before go to bed.
EDITED:
In my project I have a class Manager and that class have array of pointers to clients and orders.
The class orders receive among other things a client, that’s why I have to access that array of pointers, to choose what client to insert in the order.
In C++ there are two distinct concepts – accessibility and scope. From your question it appears that you’ve got these two concepts somewhat mixed up (I do not blame you, because they are very close to each other).
Accessibility is controlled by
private,public,protectedand so on, and can be additionally granted through “friendship”. Scope, on the other hand, is controlled by the placement of the variables and functions being accessed.In order for a member of a class to access a member of another class that other member must be in scope; it also must be accessible. It appears that you are attempting to access
_bcfromOtherClass, afriendof the class where_bcis declared. Friendship solves the accessibility part of the problem, but it does not address the scope part. In order forOtherClassto access_bc, an instance member of theManagerclass, it must have a reference of some sort to aManagerobject. There are many ways to get a reference – for example, you can pass a reference to theManagerin the constructor ofOtherClass, store it in a private variable, and access_bcthrough it, like this:This is only one way to solve the problem of scope; other ways include passing
Manageras a parameter ofOtherClass::print, making_ma pointer, making_bcstatic, and so on. The exact way depends on your requirements.