Codecademy Logo

Friend Functions and Classes

Related learning

  • Learn advanced C++ programming with preprocessor directives, operator overloading, streams, and lambda expressions.
    • With Certificate
    • Advanced.
      9 hours

C++ Friend Functions

In C++, friend functions are unique as they can access private and protected members of a class despite not being member functions. This allows greater flexibility when implementing functions that need special access to class members.

#include <iostream>
using namespace std;
class Sample {
private:
int privateData;
public:
Sample(int value) : privateData(value) {}
//Friend function declaration
friend int accessPrivateMember(Sample s);
};
// Friend function definition
int accessPrivateMember(Sample s) {
return s.privateData;
}
int main() {
Sample obj(42);
cout << "Accessed Private Data: " << accessPrivateMember(obj) << endl;
return 0;
}

C++ Friend Declarations

In C++, friend declarations allow external functions or classes to access private and protected members of another class. This is done by including the friend keyword in the class definition.

#include <iostream>
class Box {
private:
double width;
public:
friend void printWidth(Box box); // Friend function
Box(double w) : width(w) {}
};
void printWidth(Box box) {
std::cout << "Width of box: " << box.width << std::endl;
}
int main() {
Box myBox(20.5);
printWidth(myBox);
return 0;
}

Friend Function Overloading

Friend functions in C++ allow operators that require direct access to a class’s internal states to function correctly. They’re crucial for operator overloading when the operator’s functionality involves components not typically accessible from outside the class. Typically, friend functions are declared inside the class but defined externally, ensuring encapsulation while offering necessary access. Check out the example of operator+.

#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int xVal, int yVal) : x(xVal), y(yVal) {}
// Declare friend function
friend Point operator+(const Point &p1, const Point &p2);
void display() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
// Define friend function
Point operator+(const Point &p1, const Point &p2) {
return Point(p1.x + p2.x, p1.y + p2.y);
}
int main() {
Point p1(2, 3);
Point p2(4, 5);
Point p3 = p1 + p2; // Uses the overloaded operator+
p3.display(); // Outputs: (6, 8)
return 0;
}

C++ Friend Classes

In C++, a friend class is granted access to the private and protected members of another class. This allows for specific function interactions between classes that require close coupling.

#include <iostream>
using namespace std;
class ClubMember {
private:
string name;
int id;
public:
ClubMember(string memberName, int memberId) : name(memberName), id(memberId) {}
// Declaring ClubAdmin as a friend
friend class ClubAdmin;
};
class ClubAdmin {
public:
void displayMemberInfo(const ClubMember &m) {
cout << "Member Name: " << m.name;
cout << ", ID: " << m.id << endl;
}
};
int main() {
ClubMember member("Alice", 101);
ClubAdmin admin;
admin.displayMemberInfo(member);
return 0;
}

C++ friend Keyword

In C++, the friend keyword allows one class to access private members of another. However, friend relationships are not symmetric or transitive, meaning access isn’t automatically reciprocal. Each class must declare its own friend relationships explicitly.

class ClassA {
private:
int privateMemberA;
public:
ClassA() : privateMemberA(5) {}
// ClassB can access ClassA's private members
friend class ClassB;
};
class ClassB {
public:
void displayA(ClassA& objA) {
cout << "ClassA's privateMemberA: ";
cout << objA.privateMemberA << endl;
}
};
int main() {
ClassA objA;
ClassB objB;
// Outputs: ClassA's privateMemberA: 5
objB.displayA(objA);
return 0;
}

C++ Friend Functions

Friend functions within C++ enable access to class private data, enhancing efficiency while maintaining encapsulation. This allows essential manipulation of private members without exposing them to the wider program scope. Friend classes can access private and protected members of another class in which they are declared.

#include <iostream>
using namespace std;
class Box {
private:
int width;
public:
Box() : width(10) {}
// Friend function declaration
friend void printWidth(Box &);
};
void printWidth(Box &b) {
// Access private member
cout << "Width of box: " << b.width << endl;
}
int main() {
Box box;
printWidth(box);
return 0;
}

Learn more on Codecademy

  • Learn advanced C++ programming with preprocessor directives, operator overloading, streams, and lambda expressions.
    • With Certificate
    • Advanced.
      9 hours