Search code examples
c++classoopprivatefriend

C++ Friend Function Does Not Have Access To Private Member


Friend function unable to access private member of the class in which it was declared

I am trying to recreate a sample program I am reading in a book demonstrating the use of a friend function. I am getting an error in the ever annoying "Intellisense" with Visual Studio which I frankly can't stand, saying that my defined friend function does not have access to the private member in which the declaration of the friend function exists. The code in different files is as follows:

Main.cpp:

#include "stdafx.h"
#include <iostream>
#include "Budget.h"
using namespace std;

int main() {

    return 0;
}

Budget.h

#pragma once
#include "Auxi.h"

class Budget {
public:
    Budget() {
        divisionBudget = 0;
    }

    double getDivisionBudget() const {
        return divisionBudget;
    }

    void addBudget(int n) {
        divisionBudget += n;
        corporateBudget += n;
    }

    double getCorporateBudget() {
        return corporateBudget;
    }

    static void setCorporateBudget(double n) {
        corporateBudget = n;
    }

    friend void AuxillaryOffice::addBudget(double, Budget &);

private:
    static double corporateBudget;
    double divisionBudget;
};

double Budget::corporateBudget = 0;

Auxi.h

#pragma once

class Budget;
class AuxillaryOffice {
public:
    AuxillaryOffice() {
        divisionBudget = 0;
    }

    void addBudget(double n, Budget &b);

private:
    double divisionBudget;
};

Auxi.cpp

#include "stdafx.h"
#include "Auxi.h"
#include "Budget.h"

// class Budget; Do I need this here?
void AuxillaryOffice::addBudget(double n, Budget &b) {
    divisionBudget += n;
    b.corporateBudget += n; // THIS IS THE ERROR LINE
}

In the immediately above Auxi.cpp file, I am getting an error on the b.corporateBudget += n; line it says that corporateBudget is inaccessible. Is this all legal C++ code or is there something I am missing in this example?

Thanks.


Solution

  • Butget.h

    #pragma once
    #include "Auxi.h"
    
    class Budget {
    public:
        Budget() {
            divisionBudget = 0;
        }
    
        double getDivisionBudget() const {
            return divisionBudget;
        }
    
        void addBudget(int n) {
            divisionBudget += n;
            corporateBudget += n;
        }
    
        double getCorporateBudget() {
            return corporateBudget;
        }
    
        static void setCorporateBudget(double n) {
            corporateBudget = n;
        }
    
        friend void AuxillaryOffice::addBudget(double, Budget &);
    
    private:
        static double corporateBudget;
        double divisionBudget;
    };
    
    double Budget::corporateBudget = 0; // HERE ERROR!!!
    

    You should move double Budget::corporateBudget = 0 to Auxi.cpp.