Home » C++ programs » C++ class programs

C++ program to demonstrate example of friend function with class

Friend Function
Friend function is a special type of function, which declares inside the class. Friend function can access the private, protected and public data of the class.
A keyword friend is used before return type of the function declaration/prototype.

Friend function program in C++



/*C++ program to demonstrate example of friend function with class.*/
#include <iostream>
 
using namespace std;
 
class Number
{
private:
    int a;
public:
    void getNum(int x);
    //declaration of friend function
    friend void printNum(Number NUM);
 
     
};
 
//class member function definitions
void Number::getNum(int x)
{
    a=x;
}
 
//friend function definition, no need of class name with SRO (::)
void printNum(Number NUM)
{
    cout << "Value of a (private data member of class Number): " << NUM.a;
 
}
 
int main()
{
    Number nObj; //Object declaration
    nObj.getNum(1000);
    printNum(nObj);
    return 0;
}

Output

    Output:
    Value of a (private data member of class Number): 1000






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.