Friend Class

We can also use a friend Class in C++ using the friend keyword.

Syntax:

class ClassB;

class ClassA {

   // ClassB is a friend class of ClassA

   friend class ClassB;

   ... .. ...

}

class ClassB {

   ... .. ...

}

When a class is declared a friend class, all the member functions of the friend class become friend functions.

Since ClassB is a friend class, we can access all members of ClassA from inside ClassB.

However, we cannot access members of ClassB from inside ClassA. It is because friend relation in C++ is only granted, not taken.

 

Example:

#include <iostream>

using namespace std;


class Student {

private:

    string name;

    int rollNo;

    int marks1;

    int marks2;


public:

    // Constructor to initialize student details

    Student(string studentName, int studentRollNo, int m1, int m2)

        : name(studentName), rollNo(studentRollNo), marks1(m1), marks2(m2) {}

    // Declare 'Exam' as a friend class

    friend class Exam;

};

class Exam {

public:

    // Function to calculate total marks

    int calculateTotalMarks(Student student) {

        return student.marks1 + student.marks2;

    }

    // Function to display the result

    void displayResult(Student student) {

        int total = calculateTotalMarks(student);

        cout << "Result for Student:" << endl;

        cout << "Name: " << student.name << endl;

        cout << "Roll Number: " << student.rollNo << endl;

        cout << "Marks in Subject 1: " << student.marks1 << endl;

        cout << "Marks in Subject 2: " << student.marks2 << endl;

        cout << "Total Marks: " << total << endl;

        // Determine pass or fail based on marks

        if (total >= 80) {

            cout << "Status: Passed" << endl;

        } else {

            cout << "Status: Failed" << endl;

        }

    }

};


int main() {

    // Create a Student object

    Student student("Kirti", 81988, 92, 85);

    // Create an Exam object

    Exam exam;


    // Display the result using the Exam object

    exam.displayResult(student);

    return 0;

}


Output:

Run1:

Result for Student:

Name: Kirti

Roll Number: 81988

Marks in Subject 1: 92

Marks in Subject 2: 85

Total Marks: 177

Status: Passed


Process returned 0 (0x0)   execution time : 3.722 s

Press any key to continue.


Run2:

Result for Student:
Name: Kirti
Roll Number: 81988
Marks in Subject 1: 35
Marks in Subject 2: 40
Total Marks: 75
Status: Failed

Process returned 0 (0x0)   execution time : 3.361 s
Press any key to continue.


 

No comments:

Post a Comment