i declared 2 class, and with a function from one class i want to access the data in the other class but im not sure how this can be done. when i tried, i kept on getting error messages.
Printable View
i declared 2 class, and with a function from one class i want to access the data in the other class but im not sure how this can be done. when i tried, i kept on getting error messages.
You can make the class you need to access a friend of the class that is doing the accessing.
can u give an example code?
>can u give an example code?
Code:class myclass {
friend class some_class;
...
}
The following code allows a member function from one class to access the other class
if you want all the member functions of one class to access the other then include friend friendclass; in the Class definition.Code:#include <friendclass.h>
Class Myclass
{
public:
private:
friend friendclass::friendfunction(Myclass Aclass);
};
Does this allow all methods of some_class access all members of myclass, even private members of someclass?Code:class myclass {
friend class some_class;
...
er.... this code dont work
i get an message keep saying that Undefined SYmbol "access"Code:#include <iostream.h>
class myclass {
friend class yourclass;
protected:
int variable;
public:
myclass();
};
myclass :: myclass()
{
variable = 1;
}
class yourclass {
public:
yourclass();
};
yourclass :: yourclass()
{
cout << access.variable;
}
int main()
{
myclass access;
yourclass access2;
return 0;
}
if i take off access and just leave variable, it says undefined symbol "variable"
That's because yourclass has no idea what myclass variables you've declared in main.
Code:#include <iostream>
using namespace std;
class myclass {
friend class yourclass;
protected:
int variable;
public:
myclass();
};
myclass :: myclass()
{
variable = 1;
}
class yourclass {
public:
yourclass ( myclass& );
};
yourclass :: yourclass ( myclass& access )
{
cout << access.variable;
}
int main()
{
myclass access;
yourclass access2 ( access );
return 0;
}
originally posted by elad
If you make the entire class a friend then all the member functions have access to all the data including private members yes. A friend function is the same as an ordinary function except that it can access all the members of a class without restriction.Quote:
Does this allow all methods of some_class access all members of myclass, even private members of someclass?