Computer Science, asked by salmashaikh722003, 8 months ago

c++ program to define a class distance having data member as meters display the addition of two distance using friend function​

Answers

Answered by nihal7172
0

Answer:

A+ positive and yours blood group

Answered by bharatpatadia74
0

Answer:

Data hiding is a fundamental concept of object-oriented programming. It restricts the access of private members from outside of the class.

Similarly, protected members can only be accessed by derived classes and are inaccessible from outside. For example,

class MyClass { private: int member1; } int main() { MyClass obj; // Error! Cannot access private members from here. obj.member1 = 5; }

However, there is a feature in C++ called friend functions that break this rule and allow us to access member functions from outside the class.

Similarly, there is a friend class as well, which we will learn later in this tutorial.

friend Function in C++

A friend function can access the private and protected data of a class. We declare a friend function using the friend keyword inside the body of the class.

class className { ... .. ... friend returnType functionName(arguments); ... .. ... }

Example 1: Working of friend Function

// C++ program to demonstrate the working of friend function #include <iostream> using namespace std; class Distance { private: int meter; // friend function friend int addFive(Distance); public: Distance() : meter(0) {} }; // friend function definition int addFive(Distance d) { //accessing private members from the friend function d.meter += 5; return d.meter; } int main() { Distance D; cout << "Distance: " << addFive(D); return 0; }

Output

Distance: 5

Here, addFive() is a friend function that can access both private and public data members.

Though this example gives us an idea about the concept of a friend function, it doesn't show any meaningful use.

A more meaningful use would be operating on objects of two different classes. That's when the friend function can be very helpful.

C++ friend Function and friend Classes

In this tutorial, we will learn to create friend functions and friend classes in C++ with the help of examples.

Data hiding is a fundamental concept

c++ program to define a class distance having data member as meters display the addition of two distance using friend function

Explanation:

this is your answer please make me brainless I hope I can help you

Similar questions