+2 votes
17 views

Hi everyone! I am working on a sample project in c++ where I have to use friend function and inheritence. I have written the code but it is giving error. Please check it. The program is giving the the error: int B::y is private

My code is:

#include <iostream>
using namespace std;
class A
{
protected:
 int x;
public:
 A() {x = 0;}
 friend void show();
};
 class B: public A
{
public:
 B() : y (0) {}
private:
 int y;
};
 void show()
{
 A a;
 B b;
 cout << "The default value of A::x = " << a.x << " ";
 cout << "The default value of B::y = " << b.x;
}
main(){
    show();
}
by (1.4k points)   | 17 views

1 Answer

+2 votes

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.

To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows −

class Box { double width; public: double length;

  double length;
  friend void printWidth( Box box );

  void setWidth( double wid );
by (1.7k points)  
Superb, Noor!
You'r doing well

Related questions

+1 vote
2 answers
+2 votes
0 answers
asked Jun 12 by toheed (1.4k points) | 21 views
+1 vote
0 answers
asked Jun 5 by toheed (1.4k points) | 15 views
+1 vote
1 answer
asked Jun 27 by fatyma Nauman (555 points) | 44 views
+2 votes
3 answers
+2 votes
1 answer
+2 votes
1 answer
+1 vote
1 answer




Welcome to Meansflow - Where Developers and Students Learn, Share, & Build Careers, where you can ask questions and receive answers from other members of the community.
118 questions
90 answers
43 comments
111 users