-1

Cannot access the private member 'b'. This was a test problem and I can only edit a limited number of lines. This was a simple addition program, with the 3 lines highlighted by '//' left empty, this was my solution to the problem. But I am facing some errors

    #include <iostream>
    using namespace std;
    
    class Base {
        int b;
    public:
        Base(int n) : b(n) { }
        virtual void show() {        // 1
            cout << b << " ";
        }
        friend void addition (Base);                            // 2
    };
    
    class Derived : public Base {
        int d;
    public:
        Derived(int m, int n) : Base(m), d(n) { }
        void show() {
            void Base:: void show();            // 3
            cout << d << " ";
        }
    };
    
    void addition(Base &x, Base &y) {
    x.b = x.b + y.b;
}

int main() {
    int m, n;
    cin >> m >> n;

    Base *t1 = new Derived(m, n);
    Base *t2 = new Base(n);

    addition(*t1, *t2);
    t1->show();

    return 0;
}

1 Answers1

2

Your friend function is not declared correctly, you need to put the full signature:

friend void addition (Base&, Base&);

As for the call to show to base class, you only need this:

Base::show();
Guillaume Racicot
  • 32,627
  • 7
  • 60
  • 103