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.....
Re: member function of one class can be friend function of another class
Quote:
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
Quote:
Originally Posted by
VictorN
1. please, use Code tags while posting code snippets.
2. Did you try to compile this code? What does compiler say you?
I have added necessary code.
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]
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.
Re: member function of one class can be friend function of another class
Please stop using the 'friend' keyword. Wipe it from your memory. As soon ans you need the 'friend' keyword, your design is wrong.
Re: member function of one class can be friend function of another class
Quote:
As soon ans you need the 'friend' keyword, your design is wrong.
Untrue as any excessively categorical statement. An advice to use 'friend' as rare as possible would be more correct. :)