Skip to main content

Featured

C++ Program to Perform Linear Search on a Vector

  C++ Program to Perform Linear Search on a Vector Introduction In this C++ program, we will learn how to perform a Linear Search on a vector. The program first takes the size of the vector and its elements as input. Then it asks the user for the element to search. If the element is found, it displays the index where it is located. Otherwise, it displays a message indicating that the element is not found. C++ Program #include<bits/stdc++.h> using namespace std; int main() { int num, search, found = 0; cout << "Enter the size of the vector:" << endl; cin >> num; vector<int> v(num); cout << "Enter " << num << " elements in vector:" << endl; for(int i = 0; i < num; i++) { cin >> v[i]; } cout << "Enter element that you want to search:" << endl; cin >> search; for(int i = 0; i < num; i++) { ...

C++ Program to Demonstrate Friend Function

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 Sample contains a private variable x.
  • The constructor initializes x with the value 10.
  • The function show() is declared as a friend inside the class.
  • Because it is a friend, show() can access the private variable x.

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.

Comments

Popular Posts

๐ŸŒ™