GeeksforGeeks » C/C++ Programming Questions

friend and inheritance in C++

(3 posts)

Tags:

  1. geek
    guest
    Posted 8 months ago #

    Why does the following program work? show() is not a friend of class B.

    #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()
    {
        B b;
        cout << "The default value of A::x = " << b.x;
    }
    
    int main()
    {
        show();
        return 0;
    }
    
  2. geek
    guest
    Posted 8 months ago #

    Surprisingly, when I change the program to following, it fails in compilation.

    #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(B b)
    {
        cout << "The default value of A::x = " << b.x;
    }
    
    int main()
    {
        B b;
        show(b);
        return 0;
    }
    
  3. Deepesh
    guest
    Posted 4 months ago #

    X is a member of class A and class A is a friend of show function


Reply

You must log in to post.

RSS feed for this topic