Navigation



8.13 — Friend functions and classes

For much of this chapter, we’ve been preaching the virtues of keeping your data private. However, you may occasionally find situations where you will find you have classes and functions that need to work very closely together. For example, you might have a class that stores data, and a function (or another class) that displays the data on the screen. Although the storage class and display code have been separated for easier maintenance, the display code is really intimately tied to the details of the storage class. Consequently, there isn’t much to gain by hiding the storage classes details from the display code.

In situations like this, there are two options:
1) Have the display code use the publicly exposed functions of the storage class. However, this has several potential downsides. First, these public member functions have to be defined, which takes time, and can clutter up the interface of the storage class. Second, the storage class may have to expose functions for the display code that it doesn’t really want accessible to anybody else. There is no way to say “this function is meant to be used by the display class only”.

2) Alternatively, using friend classes and friend functions, you can give your display code access to the private details of the storage class. This lets the display code directly access all the private members and functions of the storage class! In this lesson, we’ll take a closer look at how this is done.

Friend functions

A friend function is a function that can access the private members of a class as though it were a member of that class. In all other regards, the friend function is just like a normal function. A friend function may or may not be a member of another class. To declare a friend function, simply use the friend keyword in front of the prototype of the function you wish to be a friend of the class. It does not matter whether you declare the friend function in the private or public section of the class.

Here’s an example of using a friend function:

class Accumulator
{
private:
    int m_nValue;
public:
    Accumulator() { m_nValue = 0; }
    void Add(int nValue) { m_nValue += nValue; }

    // Make the Reset() function a friend of this class
    friend void Reset(Accumulator &cAccumulator);
};

// Reset() is now a friend of the Accumulator class
void Reset(Accumulator &cAccumulator)
{
    // And can access the private data of Accumulator objects
    cAccumulator.m_nValue = 0;
}

In this example, we’ve declared a function named Reset() that takes an object of class Accumulator, and sets the value of m_nValue to 0. Because Reset() is not a member of the Accumulator class, normally Reset() would not be able to access the private members of Accumulator. However, because Accumulator has specifically declared this Reset() function to be a friend of the class, the Reset() function is given access to the private members of Accumulator.

Note that we have to pass an Accumulator object to Reset(). This is because Reset() is not a member function. It does not have a *this pointer, nor does it have an Accumulator object to work with, unless given one.

While this example is pretty contrived, here’s another example that’s a lot closer to something you’ll see again in the near future, when we talk about operator overloading:

class Value
{
private:
    int m_nValue;
public:
    Value(int nValue) { m_nValue = nValue; }
    friend bool IsEqual(const Value &cValue1, const Value &cValue2);
};

bool IsEqual(const Value &cValue1, const Value &cValue2)
{
    return (cValue1.m_nValue == cValue2.m_nValue);
}

In this example, we declare the IsEqual() function to be a friend of the Value class. IsEqual() takes two Value objects as parameters. Because IsEqual() is a friend of the Value class, it can access the private members of all Value objects. In this case, it uses that access to do a comparison on the two objects, and returns true if they are equal.

A function can be a friend of more than one class at the same time. For example, consider the following example:

class Humidity;

class Temperature
{
private:
    int m_nTemp;
public:
    Temperature(int nTemp) { m_nTemp = nTemp; }

    friend void PrintWeather(Temperature &cTemperature, Humidity &cHumidity);
};

class Humidity
{
private:
    int m_nHumidity;
public:
    Humidity(int nHumidity) { m_nHumidity = nHumidity; }

    friend void PrintWeather(Temperature &cTemperature, Humidity &cHumidity);
};

void PrintWeather(Temperature &cTemperature, Humidity &cHumidity)
{
    std::cout << "The temperature is " << cTemperature.m_nTemp <<
        " and the humidity is " << cHumidity.m_nHumidity << std::endl;
}

There are two things worth noting about this example. First, because PrintWeather is a friend of both classes, it can access the private data from objects of both classes. Second, note the following line at the top of the example:

class Humidity;

This is a class prototype that tells the compiler that we are going to define a class called Humidity in the future. Without this line, the compiler would tell us it doesn’t know what a Humidity is when parsing the prototype for PrintWeather() inside the Temperature class. Class prototypes serve the same role as function prototypes — they tell the compiler what something looks like so it can be used now and defined later. However, unlike functions, classes have no return types or parameters, so class prototypes are always simply class ClassName, where ClassName is the name of the class.

Friend classes

It is also possible to make an entire class a friend of another class. This gives all of the members of the friend class access to the private members of the other class. Here is an example:

class Storage
{
private:
    int m_nValue;
    double m_dValue;
public:
    Storage(int nValue, double dValue)
    {
        m_nValue = nValue;
        m_dValue = dValue;
    }

    // Make the Display class a friend of Storage
    friend class Display;
};

class Display
{
private:
    bool m_bDisplayIntFirst;

public:
    Display(bool bDisplayIntFirst) { m_bDisplayIntFirst = bDisplayIntFirst; }

    void DisplayItem(Storage &cStorage)
    {
        if (m_bDisplayIntFirst)
            std::cout << cStorage.m_nValue << " " << cStorage.m_dValue << std::endl;
        else // display double first
            std::cout << cStorage.m_dValue << " " << cStorage.m_nValue << std::endl;
    }
};

Because the Display class is a friend of Storage, any of Display’s members that use a Storage class object can access the private members of Storage directly. Here’s a simple program that shows the above classes in use:

int main()
{
    Storage cStorage(5, 6.7);
    Display cDisplay(false);

    cDisplay.DisplayItem(cStorage);

    return 0;
}

This program produces the following result:

6.7 5

A few additional notes on friend classes. First, even though Display is a friend of Storage, Display has no direct access to the *this pointer of Storage objects. Second, just because Display is a friend of Storage, that does not mean Storage is also a friend of Display. If you want two classes to be friends of each other, both must declare the other as a friend. Finally, if class A is a friend of B, and B is a friend of C, that does not mean A is a friend of C.

Be careful when using friend functions and classes, because it allows the friend function or class to violate encapsulation. If the details of the class change, the details of the friend will also be forced to change. Consequently, limit your use of friend functions and classes to a minimum.

8.14 — Anonymous variables and objects
Index
8.12 — Static member functions

55 comments to 8.13 — Friend functions and classes

  • sanjay

    hey its great to have a website like this
    i didn’t buy my cp book till my exams even then i stood 3rd in my class…


    sanjay

  • jagadeesh

    c++ programm.
    member function of class can access private members,than we we need friend function,what is the use of this please iam in confusion

    • Making a function a friend of some class means that function has access to the classes private member variables (even though that function is not a member of the class). The Humidity/Weather example above shows an example of this: PrintWeather() is using the private members of Humidity and Weather (which it would normally not have access to, because they are private). However, it is allowed to do this because it has been made a friend.

  • K D Joshi

    Is it compulsory to declare a function(which is required to be a friend function) in that class itself?
    Suppose there is a class named FUN. It has some private and some public elements. Now I want a function called SOME to be a friend of FUN. So, is it MUST to declare SOME in private or public section of FUN? Or is it okey to declare and define it entirely outside the class with prefix friend.

  • #include<iostream>
    using namespace std;
    class x
    {
    	int a,b;
    
    	public:
    		x()
    	{
    		a=5;
    		b=9;
    	}
    
    	friend ostream& operator<<(ostream &, x);
    };
    
    ostream& operator<<(ostream &t, x x1)
    {
    	t<<x1.a;
    	t<<x1.b;
    	return t;
    }
    void main()
    {
    	x x1;
    	cout<<x1;
    }
    

    why the errors this above code contain.plz explain .

  • Pathik

    Are all the codes you write now object-oriented programming?

  • tyler

    hey Alex;

    great lessons, and thx for helping me back with the headers files.

    I would like to know how to make my program play music that i have on my computer, and dicplay pictures. when i saw ‘Object Oriented Programing’ thats what i though it was (useing picures in prgramsect…) gut i see that i was wrong. i would like to learn how to make those types of gams that you see on miniclip. ( i know i know, those games are made using flash, but i’m sure you can do simalar thins with C++, like they use C++ for games likie need for speed and the computer version of halo don’t they?)

  • Trevor

    Heya Alex, I really had better start by thanking you for this excellent site. Thanks.

    My question is: is it possible to make only one fuction in a Class A a friend of Class B without making the WHOLE of Class A a friend of Class B. I’ve constructed a crude example to show why I think it can’t be done, perhaps you can tell me if I’m doing something wrong:

    
    #include "stdafx.h"
    #include <iostream>
    
    class number
    {
    private:
    	int no;
    public:
    	number(int n=0){no = n;}
    	friend class manipulate;
    };
    
    class manipulate
    {
    public:
    	int add(number &a,number &b)
    	{
    		return a.no + b.no;
    	}
    	int sub(number &a,number &b)
    	{
    		return a.no - b.no;
    	}
    };
    
    int main()
    {
    	using namespace std;
    
    	number a(4),b(2);
    	manipulate name;
    
    	cout << name.add(a,b) << endl;
    }
    

    The code above works exactly as expected, but if I replace “friend class manipulate” with “friend int add(number &a,number &b)” or “friend int manipulate::add(number &a,number &b)”, I get compiler errors along the lines of “cannot access private member declared in class ‘number’”.

    Cheers,

    Trevor

  • Otman

    //Main.cpp

    #include
    #include "cEmployee.h"
    #define MAX 5

    using namespace std;

    int main()
    {
    Employee staffs[MAX];
    char strTemp[255];
    unsigned nTemp;
    double dTemp;
    for (int i = 0; i < MAX; ++i)
    {
    cout << "Employee " << i + 1 << endl;
    cout <> strTemp;
    staffs[i].setEmployeeName(strTemp);
    cout <> nTemp;
    staffs[i].setEmployeeId(nTemp);
    cout <> dTemp;
    staffs[i].setEmployeeSalary(dTemp);
    }
    cout << endl;

    for (int i = 0; i < MAX; ++i)
    {
    cout << "Employee " << i + 1 << endl;
    cout << "Employee name : " << staffs[i].getEmployeeName() << endl;
    cout << "Employee ID : " << staffs[i].getEmployeeId() << endl;
    cout << "Employee Salary : " << staffs[i].getEmployeeSalary() << endl << endl;
    }
    cout << "Total objects instantiated is : " << Employee::getEmployees() << endl;
    cin.get();
    cin.get();
    return 0;
    }

    // Employee.h

    #ifndef EMPLOYEE_H
    #define EMPLOYEE_H

    class Employee
    {
    public:
    Employee();
    Employee(char* employee_name, unsigned employee_ID, double emplyee_salary);
    ~Employee();
    void initEmployee(void);
    void setEmployeeName(char* employee_name);
    void setEmployeeId(unsigned employee_ID);
    void setEmployeeSalary(double employee_salary);
    char* getEmployeeName(void) const;
    unsigned getEmployeeId(void) const;
    double getEmployeeSalary(void) const;
    static unsigned getEmployees(void);
    friend void resetEmployee(Employee& ex, char* newName);
    private:
    static unsigned nEmployees;
    unsigned nEmployeeClassId;
    char* strEmployeeName;
    unsigned nEmployeeId;
    double dEmployeeSalary;
    };

    #endif

    // Employee.cpp

    #include "cEmployee.h"
    #include
    #include

    using namespace std;

    void Employee::initEmployee(void)
    {
    nEmployeeClassId = ++nEmployees;
    nEmployeeId = 5000 + nEmployeeClassId;
    dEmployeeSalary = 0.0;
    }

    Employee::Employee()
    {
    strEmployeeName = 0;
    initEmployee();
    }

    Employee::Employee(char* strEmployeeName, unsigned nEmployeeId, double dEmployeeSalary)
    {
    strEmployeeName = new char[strlen(strEmployeeName) + 1];
    strcpy(this->strEmployeeName, strEmployeeName);
    this->nEmployeeId = nEmployeeId;
    this->dEmployeeSalary = dEmployeeSalary;
    }

    Employee::~Employee()
    {
    if (strEmployeeName != 0)
    {
    delete [] strEmployeeName;
    strEmployeeName = 0;
    }
    }

    void Employee::setEmployeeName(char* strEmployeeName)
    {
    if (this->strEmployeeName != 0)
    {
    delete [] this->strEmployeeName;
    this->strEmployeeName = 0;
    }
    this->strEmployeeName = new char[strlen(strEmployeeName + 1)];
    strcpy(this->strEmployeeName, strEmployeeName);
    }

    void Employee::setEmployeeId(unsigned nEmployeeId)
    {
    this->nEmployeeId = nEmployeeId;
    }

    void Employee::setEmployeeSalary(double dEmployeeSalary)
    {
    this->dEmployeeSalary = dEmployeeSalary;
    }

    char* Employee::getEmployeeName(void) const
    {
    return strEmployeeName;
    }

    unsigned Employee::getEmployeeId(void) const
    {
    return nEmployeeId;
    }

    double Employee::getEmployeeSalary(void) const
    {
    return dEmployeeSalary;
    }

    unsigned Employee::getEmployees(void)
    {
    return nEmployees;
    }

    unsigned Employee::nEmployees = 0; //Static variable difinition

    void renameEmployee(Employee& ex, char* newName)
    {
    strcpy(ex.strEmployeeName, newName);
    }

    
    I don't know why friend function here don't work, i got an error [BCC32 Error] cEmployee.cpp(82): E2247 'Employee::strEmployeeName' is not accessible.
    • Quinn

      Get the <pre> tags right next time! :) It was hard to copy/paste this code in my compiler and try it since the stylized quotation marks (“”) are different characters than the standard ones gcc compiles. Anyway, the problem is you neglected to make void renameEmployee a friend function. That’ll get it to compile. At least that’s all I had to do, though the design of this program can do some work, liberal use of “friend” isn’t advised.

    • B.Arunkumar

      declare the EmployeeName variable as static in nature

  • dfdhdfhjhf

    In your second example at line 7 you mistyped the bool to boo.

  • Kamesh

    Hello Alex,
    If I create a class and wish to provide access to private data of this class, I declare friend function. Is it required to define the function also or can we leave it for the user of the class to define the function if he/she needs to access the private variables? Thank you.

  • asif
    	#include <iostream>
    	using namespace std;
    
    	class two;
    
    	class one
    	{
     	   private:
    		int data1;
    	   public:
    		one()
    		{
    		  data1 = 100;
    		}
    	   friend int two::accessboth(one a);
    	};
    
          	class two
    	{
    	   private:
    		int data2;
    	   public:
    		two()
    		{
    		  data2 = 200;
    		}
     	   int accessboth(one a);
            };
    
             int two::accessboth(one a)
              {
    	    return (a.data1 + (*this).data2);
    	  }
    
    	int main()
    	{
    	   one a;
    	   two b;
    	   cout << b.accessboth(a);
    	   return 0;
    	}
    

    can some one help me with this …..i tried compiling in Gnu G++ environment…and following are the errors…can someone tell me whats wrong with above code!!!111
    friend2.cpp:30: error: invalid use of incomplete type ‘struct two’
    friend2.cpp:5: error: forward declaration of ‘struct two’
    friend2.cpp: In member function ‘int two::accessboth(one)’:
    friend2.cpp:24: error: ‘int one::data1’ is private
    friend2.cpp:55: error: within this context

    • Anupama

      I guess its because u are making a function of class Two friend of Class One. I don think this
      is allowed. This code will work if u replace

       friend int two::accessboth(one a);

      with

      friend Class Two 

      Please verify

  • rashmi.N

    i need a program to illustrate friend function and friend class in a single program.plz help fast…..

  • Pradeep

    Hi Alex,

    Cant I define the friend function in the class Itself.

    I mean total implemetation of the function inside the class.

  • lolo 33

    I’m so lucky to find this websit =)

    thnx so much Alex ,i have c++ exam now

    bye

  • i am judio gotta our game dvd james foster our redgirftoin judio gotta money michelle deporilte becky’s prenuring serft teacher mother friend our monery swchool high school buniess work school did pronuring serft teacher mother friend school buniess work high school flase ture pronuring secert’s back’s iam bad’s mjad’s did can’s happy ;puppyracesad white page’s.

  • June

    Hi Alex, thanks for the nice website. I am new to C++, and I am confused with the arguments passed to friend function. Why a reference of the object is passed (hope I get this correct), other than the object itself?
    Thanks.

  • i am can’t johnston high school gragdering 2007 age21old bye august 2008 Aridteuas 2009 age22old 2010 aridteuas age23old work buniess school check briawood meadow number s.s.n. more Aridteuasage age24old 2011 age25old 2012 age26old 2013 age27old 2014 age28old 2015 age29old 2016 age30old 2017 age31old 2018 age32old 2019 age33old 2020 age34old 2021 age35old 2022

  • more names i is tatiana nashira rocchio tatian bye gradanday june 08 2007 age21old may 2008 summber Aridteua work buniess school age22old 2009 age23old2010 age24old2011 age25old 2012 age26old 2013 age27old 2014 age28old 2015 age29old 2016 age30old 2017 age31old 2018 age32old 2019 age33old 2020 age34old 2021 age35old 2022 age36old 2023 age37old 2024 age38old 2025 age39old 2026 age40old 2027 age41old age42old more april 14,1987 age old aridteuas work buniess school check briawood meadow s.s.n. i you can’t summer mrs.neusa mr.neusa mr.teacher mrs.teacher mother friend father friend you can’t gift money dollar name tatiana nashira rocchio deana dsina happy halloween day thanksgiving happy holiday

  • integral
    <class Value
    {
    private:
        int m_nValue;
    public:
        Value(int nValue) { m_nValue = nValue; }
        friend boo IsEqual(const Value &cValue1, const Value &cValue2);
    };
    
    boolean IsEqual(const Value &cValue1, const Value &cValue2)
    {
        return (cValue1.m_nValue == cValue2.m_nValue);
    }
    
  • Dr. Jekyll

    To alex

    When learning from the excellent tutorials on this website I have found that the examples can be difficult to understand when learning a new topic because of the similar names for variables, classes, functions and members ect. For example in 8.13 Friend functions and classes…

    class Value
    {
    private:
        int m_nValue;
    public:
        Value(int nValue) { m_nValue = nValue; }
        friend bool IsEqual(const Value &cValue1, const Value &cValue2);
    };
    
    bool IsEqual(const Value &cValue1, const Value &cValue2)
    {
        return (cValue1.m_nValue == cValue2.m_nValue);
    }
    
    Perhaps something like this would be easier to understand to a newbie who is just trying to get their head around what things in the code are.
    
    class Animal
    {
    private:
        int m_nNumOfLegs;
    public:
        Animal(int nNumOfLegs) { m_nNumOfLegs = nNumOfLegs; }
        friend bool IsEqualNumLegs(const Animal &cPig, const Animal &cDog);
    };
    
    bool IsEqualNumLegs(const Animal &cPig, const Animal &cDog)
    {
        return (cPig.m_nNumOfLegs == cDog.m_nNumOfLegs);
    }
    
    		
  • arun aravindan

    why to use friend function?

  • arun aravindan

    hello anyone please answer ,why should we use friend function?

  • shashank dwivedi

    First i would like to thank for such a comprehensive website on oop.
    I really dont know what’s problem in code.it gives errors when i compile it in Codeblocks GCC compiler.Please help me out. :)

    #include
    using namespace std;
    class overload1
    {
    private:
    int a,b;
    public:
    overload1(){}
    overload1(int,int);
    overload1 operator+(overload1);//first object passed implicitly and second explicitly.
    friend void display(overload1,overload2);//making a function friend
    friend class overload2;//making a class friend
    };
    class overload2
    {
    overload2(){}
    overload2(int,int);
    friend overload2 operator-(overload2,overload2);//operator overload using friend both objects passed explicitly.
    friend void display(overload1,overload2);
    };
    overload1::overload1(int x=0,int y=0)
    {
    a=x;
    b=y;
    }
    overload2::overload2(int x=0,int y=0)
    {
    a=x;
    b=y;
    }
    overload1 overload1::operator+(overload1 obj)
    {
    overload1 temp;
    temp.a=a+obj.a;
    temp.b=b+obj.b;
    return temp;
    }
    overload2 operator-(overload2 obj1,overload2 obj2)
    {
    overload2 temp;
    temp.a=obj1.a-obj2.a;
    temp.b=obj1.b-obj2.b;
    return temp;
    }
    void display(overload1 o1,overload2 o2)//scope resolution not used here.
    {
    cout<<"sum is: "<<o1.a<<endl;
    cout<<"sum is: "<<o1.b<<endl;
    cout<<"sub is: "<<o2.a<<endl;
    cout<<"sub is: "<<o2.b<<endl;
    }
    int main()
    {
    overload1 ob11(5,6),ob12(2,3),ob13;
    overload2 ob21(5,6),ob22(2,3),ob23;
    ob13=ob11+ob12;
    ob23=ob21-ob22;
    display(ob13,ob23);
    return 0;
    }

  • shashank dwivedi

    @arun arivindan
    Hi though i am new to cpp,i think i can answer your doubt.
    It is not advised to use friend function unless it is really very necessary to do so
    as it kills basic property of object-oriented programming “Encapsulation”.
    Thus it makes your code less secure and vulnerable.
    Though it is sometimes necessary for a external function to access private members
    of a class for its functionality,in such cases we are not left with choices and
    declare them friend to that particular class.
    Hope you got it. :)

  • fakhri

    int * change(int y)
    {
    y++;
    return &y;
    }
    void main()
    {
    int *p;
    int x=7;
    p=change(x);
    cout<<*p<<x<<endl;
    }

    output:
    77
    but when i use
    cout<<x<<*p;
    output:
    78
    Any one can tell the reason
    and how it is work?

  • Aki

    Normal friend functions can access private members of other classes.
    But if the friend function is a member function of another class then it cannot access the other class’s private members.

    
    #include <iostream>
    class A
    {
    	int x;
    	public:
    	friend int boo(A &a);
    	A()
    	{
    		x = 5;
    	}
    };
    
    //int boo(A &a)
    //{
    //	return a.x;
    //}
    class B
    {
    	public:
    	int y;
    	int boo(A &a)
    	{
    		y = a.x;
    		return y;
    	}
    };
    
    int main()
    {
    	using namespace std;
    	A a;
    	B b;
    	cout << b.boo(a) << endl;
    }
    
    It gives the following error
    
    

    friends.cpp: In member function ‘int B::boo(A&)’:
    friends.cpp:4:6: error: ‘int A::x’ is private
    friends.cpp:23:9: error: within this context

    • prakash

      // This works.

      #include
      #include

      class A; // forward declaration

      class B
      {
      public:
      int y;
      int boo(A &a) ; // only declare. define later. as friendship has not came in to play yet.

      };

      class A
      {
      int x;
      public:
      friend int B::boo(A &a);
      A()
      {
      x = 5;
      }
      };

      // now we define the function boo which belongs to class B only. just defined outside.
      // if using header files and implementation files separately, it makes crystal clear.

      int B::boo(A &a){
      y = a.x;
      return y;
      }

      int main()
      {
      using namespace std;
      A a;
      B b;
      cout << b.boo(a) << endl;
      }

      • prakash

        Aki,

        you can add more functions in class B, same as foo. i.e. declare first and define later.
        but keep friendship to foo.
        other functions will not have access to private x

        -prakash

  • nadia.16

    salve non riesco a risovere qst classe qualcuno mi può dare una mano? grazieeedevo creare una classe SistemaOperativo con le seguenti variabili:
    NomeSistemaOperativo(stringa),Versione(float)
    definire un costruttore per inizializzare i valori.
    devo creare una classe Fotocamera:
    Risolzione(int) Zoom(float)
    con get e set
    classe Smartphone che includa :
    istanza della classe SistemaOperativo
    istanza della classe Fotocamera
    una variabile MemoriaInterna (float)
    relazione di amicizia tra classe Smartphone e Fotocamera
    creare un applicazione per istanziare e modificare oggetto della classe Smartphone.

  • nadia.16

    salve non riesco a risovere qst classe qualcuno mi può dare una mano? grazidev o creare una classe SistemaOperativo con le seguenti variabili:
    NomeSistemaOperativo(stringa),Versione(float)
    definire un costruttore per inizializzare i valori.
    devo creare una classe Fotocamera:
    Risolzione(int) Zoom(float)
    con get e set
    classe Smartphone che includa :
    istanza della classe SistemaOperativo
    istanza della classe Fotocamera
    una variabile MemoriaInterna (float)
    relazione di amicizia tra classe Smartphone e Fotocamera
    creare un applicazione per istanziare e modificare oggetto della classe Smartphone.

  • nadia.16

    #include
    #include
    using namespace std;
    class SistemaOperativo{
    public:
    string NomeSistemaOperativo;
    float Versione;
    void inserisci_Nome();
    void inserisci_Versione();
    };
    class Fotocamera{
    public:
    int Risoluzione;
    float Zoom;
    int getRisoluzione();
    int setRisoluzione();
    float getZoom();
    float setZoom();
    #include
    #include “classi.h”;
    void SistemaOperativo::inserisci_Nome(){
    cout<<"inserire nome del SistemaOperativo:";
    cout<<endl;
    };
    void SistemaOperativo::inserisci_Versione(){

    cout<<"inserire versione del SistemaOperativo:";
    cout<<endl;

    };
    void Fotocamera::getZoom(){
    cout<<"impostare zoom della Fotocamera:";
    cout<<endl;
    Zoom=zoom;
    return zoom;
    }
    void Fotocamera::setZoom() {
    cout<<"impostare zoom della Fotocamera:";
    cout<<endl;
    Zoom=zoom;
    return zoom;
    }
    void Fotocamera::getRisoluzione(){
    cout<<"impostare Risoluzione della Fotocamera:";
    cout<<endl;
    Risoluzione=risoluzione;
    return risoluzione;
    }
    void Fotocamera::setRisoluzione(){
    cout<<"impostare Risoluzione della Fotocamera:";
    cout<<endl;
    Risoluzione=risoluzione;
    return risoluzione;
    }

    main(){
    SistemaOperativo sistemaoperativo;
    sistemaoperativo.inserisci_Nome();
    sistemaoperativo.inserisci_Versione();
    cout<<"il Nome del SistemaOperativo è:"<<sistemaoperativo.nome;
    cout<<"la Versione del SistemaOperativo è:"<<sistemaoperativo.versione;
    Fotocamera fotocamera;
    fotocamera.getRisoluzione();
    fotocamera.setRisoluzione();
    fotocamera.getZoom();
    fotocamera.setZoom();

    cout<<"la Risoluzione della Fotocamera è:"<<fotocamera.risoluzione;
    cout<<"lo Zoom della Fotocamera è:"<<fotocamera.zoom;
    return 0;
    }
    };

    devo creare una classe amico tra wqst due classi ma non compila

  • nadia.16

    come posso risolvere qlkn mi dà una mano?

  • dinhpq

    Hi Alex,
    I have confused “A friend function may or may not be a member of another class” It mean member function Reset() of class Value may or may not be a friend class Accumulator, is that true? I have an example:

    #include
    using namespace std;
    
    class Accumulator
    {
    private:
        int m_nValue;
    public:
        Accumulator() { m_nValue = 0; }
        void Add(int nValue) { m_nValue += nValue; }
        friend void Reset(Accumulator &cAccumulator);
    };
    
    class Value
    {
    private:
        int m_nValue;
    public:
        Value(int nValue) { m_nValue = nValue; }
        void Reset(Accumulator &cAccumulator);
    };
    void Reset(Accumulator &cAccumulator)
    {
        cout << "Reset Accumulator" <<endl;
        cAccumulator.m_nValue = 0;
    }
    int main()
    {
    	Accumulator cAccumulator;
    	Value cValue(10);
    	cValue.Reset(cAccumulator);
       return 0;
    }
    

    The compiler error: undefined reference to `Value::Reset(Accumulator&)’
    Can you explain?

  • samiullah

    Thank U so much Alex;

  • Vaibhav

    Hi Alex,

    Just a question.
    Can a friend function be const or volatile.
    eg. friend void Reset(Accumulator &cAccumulator) const;
    friend volatile void Reset((Accumulator &cAccumulator);

You must be logged in to post a comment.