member function of one class can be friend function of another class
How to make a member function of one class , the friend function of another class:
class car
{
private:
int speed;
char color[20];
public:
void input()
{
cin >> color >> speed;
}
void display(car c)// Member function of Class car, which i want to make friend function for Class Scooter
{
cout << c.color << endl << c.speed;
}
};
class scooter
{
public:
int input_i()
{
cin >> color >> speed;
}
friend void car::display(scooter); // I am trying to make the member function display() of Class car , friend function for Class scooter.
};
void display(scooter s)
{
cout << s.color << s.speed;// compiler error color and speed undeclared.
}
// I want to make color and speed visible in Scooter class my making display function , friend function of class scooter.
void main()
{
car c1;
scooter s1;
c1.input();
s1.input_i();
c1.display(c1);
s1.display(s1);
}
[In the above program i want to make the member function display() of class Car , the friend function for class Scooter, so that class scooter can access private data members(speed and color) of class Car.]
But i think there's a mistake in above coding , so please help me how i could do this, as compiler error: nonexistent function 'car::display' specified as friend
THANKS.....
Last edited by Tanushreeagr; June 1st, 2012 at 01:34 AM.
Re: member function of one class can be friend function of another class
Originally Posted by Tanushreeagr
M...
[ In the above program : friend void car::display(scooter); Is this the correct way to make member function of one class , friend function of another class.?]
1. please, use Code tags while posting code snippets.
2. Did you try to compile this code? What does compiler say you?
Re: member function of one class can be friend function of another class
No you haven't. The post still lacks code tags [code]Properly indented code here[/code]
Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it.
- Brian W. Kernighan
Re: member function of one class can be friend function of another class
I suspect that the correct way to solve your real problem (not the one stated here - that is just due to the way you are approaching this) is to have a base class (e.g. vehicle) which contains the speed and color fields, and the method display. Then derive car and scooter classes from this.
Bookmarks