Friend Function in Multiple Classes (OOP with C++) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Friend Function in Multiple Classes (OOP with C++)

Hi! I just want to learn friend function syntax in multiple classes, properly. According to what I've learned from the online courses, first of all we should define friend function to each classes in which we want to use it. When we do that, we write (for example) 'friend void functionname (classname1, classname2);'. But when I write this comment line I get an error in different compilers. So, because of that, compiler cannot run the program but even the error, codelite (one of the IDE) can run the program. In addition, when I change comment line as 'friend void functionname (classname_whichclass_I_am_in); problem solves, program runs without any error in every compiler. But I google the syntax of friend function and the true defining of ff is the first one which gives me errors. May you help me to figure out? The error I get: Unknown type name 'classname2' My complete program: https://code.sololearn.com/c4EXMSVMQMa0/?ref=app

18th May 2019, 5:42 PM
Sultan Nur Korkusuz Güçük
Sultan Nur Korkusuz Güçük - avatar
6 Answers
+ 4
Ipang Thank you so much for your help😊
18th May 2019, 6:52 PM
Sultan Nur Korkusuz Güçük
Sultan Nur Korkusuz Güçük - avatar
+ 4
You're welcome Sultan Nur Korkusuz 😁
18th May 2019, 7:00 PM
Ipang
+ 3
Sultan Nur Korkusuz Thanks for sharing the code 👍 Please don't mark my answer, I haven't helped you with anything just yet. ~ swim ~ Is forward declaration necessity be the problem here? I see the `bus` class is defined before `microbus` class. What do you think bro?
18th May 2019, 6:13 PM
Ipang
+ 2
Seems to me probably not having a declaration or definition of `classname2` be the cause, rather than the function signature (from the error message). But to be clear, I suggest you share your code link on the Description of your original question, so more people can help clear the doubt. (Edit) Also add C++ in the Relevant Tags
18th May 2019, 5:56 PM
Ipang
+ 2
Thank you so much. I've added the link as you suggested me to be more clear. Edit again for relevant tags
18th May 2019, 6:02 PM
Sultan Nur Korkusuz Güçük
Sultan Nur Korkusuz Güçük - avatar
+ 2
~swim~ Thanks to you I figure out the problem😊 I'll always declare the class before friend function comment line.👍
18th May 2019, 6:55 PM
Sultan Nur Korkusuz Güçük
Sultan Nur Korkusuz Güçük - avatar