Skip to content

Instantly share code, notes, and snippets.

@rugbyprof
Created September 14, 2024 07:17
Show Gist options
  • Save rugbyprof/2b1d02ad0815ce247cc610fc42ad9d54 to your computer and use it in GitHub Desktop.
Save rugbyprof/2b1d02ad0815ce247cc610fc42ad9d54 to your computer and use it in GitHub Desktop.
Simple Example of the Friend keyword in C++. Not much practicality but its different than using it for ostream.
// THIS CODE WILL ERROR
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class A {
private:
int private_part;
public:
A() : private_part{rand() % 100} {}
friend class B;
};
class B {
private:
int some_value;
A a;
public:
B() : some_value{rand() % 100} {}
void PrintPrivateParts(A privates) {
cout << "A's private_part:" << privates.private_part << endl;
}
};
class Grades {
private:
vector<int> grades;
public:
Grades(){};
Grades(vector<int> grades) : grades{grades} {}
void addGrade(int g) { grades.push_back(g); }
friend class Printer;
int size() { return grades.size(); }
};
struct Printer {
void printGrades(Grades g) {
for (auto g : g.grades) {
cout << g << " ";
}
}
};
// Driver program
int main() {
A a;
B b;
b.PrintPrivateParts(a);
Grades G({77, 88, 99, 78, 98, 68});
Printer P;
P.printGrades(G);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment