-
Freind function
Code:
class A
{
private:
int a;
punlic:
friend ostream & operator<<(ostream &os, const A &object);
};
ostream & operator<<(ostream &os, const A &object)
{
os << object.a;
return osl;
}
class B: public class A
{
public:
freind ostream & operator<<(ostream &os, const B &object)
{
os << object.a ;
}
};
In class A, I have the friend function, and use it to print out the private instance variable a.
Now, in class B, I would like to print out the variable a, which is inherited from class A, but I get an error when I try objcet.a, in class B, How can I access the variable a, using the friend function in class B?
Thanks
-
You have lot of spelling errors but I'm sure you are fully aware of them. You need to make the variable in class A "protected" not private. Only protected and public members and methods get inherited. Try that and it should work.
-
I didnt want to throw all my code up there, so I just showed what I needed.
One more question. If I make them protected they will be accessible to derived classes but not in main?
Thanks
-
Correct, main will still NOT be able to access them as if they were private, but your derived classes will be able to access them freely.
-
There's no need as I see it to allow the derived class direct access to the base member variables....the only action is to print value (not manipulate it directly), and the functionality is presented fine in the base class...therefore I would leave it as is...
Also note that B is derived from A...therefore references to B can be passed as a param to operator<<()
Code:
#include <iostream>
using std::ostream;
using std::cout;
using std::endl;
class A{
int a;
friend ostream& operator<<(ostream &os, A &object);
public:
A(int _a):a(_a){}
};
class B: public A{
public:
B(int _b):A(_b){}
};
ostream& operator<<(ostream &os, A &object){
os << object.a;
return os;
}
int main() {
A a(10);
B b(15);
cout << a << " " << b << endl;
}