Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! ๐ ๐นLearn advanced coding techniques in C& C++ ๐นMaster Linux internals & shell scripting ๐นDeep dive into Data Structures & Algorithms ๐นExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) ๐นGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
C++ Program to Demonstrate Friend Function
C++ Program to Demonstrate Friend Function
#include <iostream>
using namespace std;
class Sample
{
int x;
public:
Sample()
{
x = 10;
}
friend void show(Sample s);
};
void show(Sample s)
{
cout << "Value of x = " << s.x << endl;
}
int main()
{
Sample obj;
show(obj);
return 0;
}
๐ Explanation:
This program demonstrates the concept of a friend function in C++. A friend function is not a member of the class, but it can access the private and protected data members of the class.
- The class
Samplecontains a private variablex. - The constructor initializes
xwith the value 10. - The function
show()is declared as a friend inside the class. - Because it is a friend,
show()can access the private variablex.
Friend functions are mainly used when a function needs access to class data but does not logically belong to the class.
๐งพ Sample Output:
Value of x = 10
๐ Keywords:
C++ friend function, accessing private members, C++ OOP concepts, friend function example, C++ classes and objects
๐ Hashtags:
#CPlusPlus #FriendFunction #OOP #CPPBasics #Programming #1printf
๐ Search Description:
Learn how friend functions work in C++ with a simple example that accesses private data members. Includes explanation, output, and dark-themed code.
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment