Skip to main content

Featured

Mastering Hollow Square Patterns in C: Stars, Numbers, Alphabets & Binary

πŸ”’ C Program to Print Hollow Continuous Number Square πŸ“„ Source Code: #include <stdio.h> int main() { int num, k = 0; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { if(i == 1 || i == num || j == 1 || j == num) { // k increments sequentially only along the borders printf("%d ", k++); } else { printf(" "); } } printf("\n"); } return 0; } πŸ“‹ Copy Code πŸ’» Expected Output (Input: 5): Enter the number: 5 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 πŸ”’ C Program to Print Standard Hollow Binary Row Square πŸ“„ Source Code (Fixed Specifier): #include <stdio.h> int main() { ...

C++ Program to Demonstrate Friend Function with Two Classes

 

C++ Program to Demonstrate Friend Function with Two Classes

C++ Program to Demonstrate Friend Function with Two Classes


#include <iostream>
using namespace std;

class A;
class B;

class A
{
    int x;
public:
    A()
    {
        cout << "Enter the value of x: ";
        cin >> x;
    }
    friend void show(A obj1, B obj2);
};

class B
{
    int y;
public:
    B()
    {
        cout << "Enter the value of y: ";
        cin >> y;
    }
    friend void show(A obj1, B obj2);
};

void show(A obj1, B obj2)
{
    cout << "The value of x = " << obj1.x
         << " and y = " << obj2.y << endl;
}

int main()
{
    A obj1;
    B obj2;
    show(obj1, obj2);
    return 0;
}
  

πŸ“˜ Explanation:

This program demonstrates a friend function shared by two different classes in C++. The function show() is declared as a friend in both classes A and B.

  • Class A contains a private data member x.
  • Class B contains a private data member y.
  • The function show(A, B) is declared as a friend in both classes.
  • Because of friendship, show() can access private members of both classes.

This technique is useful when a single function needs to work with data from multiple classes without being a member of either class.

🧾 Sample Output:

Enter the value of x: 5
Enter the value of y: 10
The value of x = 5 and y = 10
  

πŸ”‘ Keywords:

C++ friend function with two classes, accessing private members, C++ OOP concepts, friend function example, C++ classes

πŸ“Œ Hashtags:

#CPlusPlus #FriendFunction #OOP #CPPBasics #Programming #1printf

πŸ” Search Description:

Learn how a friend function works with two classes in C++. This example shows how a single function can access private data of multiple classes with clear explanation and output.

Comments

Popular Posts

πŸŒ™