Welcome to this comprehensive guide on C++ Friend, Inheritance, and their differences! Let's embark on a fascinating journey of object-oriented programming in C++. š
A C++ friend function or a class has special access to the private and protected members of another class, without being a part of that class.
class MyClass {
// private member
int privateData;
// friend function
friend void printPrivate(MyClass &obj);
};
void printPrivate(MyClass &obj) {
std::cout << "Private data: " << obj.privateData << std::endl;
}In the above example, printPrivate function is a friend of MyClass and can access its private data.
Inheritance is a mechanism where one class (child or derived class) acquires the properties and methods of another class (parent or base class).
class Base {
public:
int baseData;
void printBase() {
std::cout << "Base data: " << baseData << std::endl;
}
};
class Derived : public Base {
public:
int derivedData;
void printDerived() {
std::cout << "Derived data: " << derivedData << std::endl;
}
};
int main() {
Derived derivedObj;
derivedObj.baseData = 10;
derivedObj.printBase();
derivedObj.derivedData = 20;
derivedObj.printDerived();
return 0;
}In the above example, Derived inherits properties and methods from Base.
Access: Friends have special access to private and protected members, while inheritance allows accessing public, protected, and private members.
Functionality: Friends are used to provide additional functionality to a class, while inheritance is used to create new classes from existing ones.
Usage: Use friends when you need to write functions that work with a specific class but are not a part of that class. Use inheritance when you want to create a new class that is a modified version of an existing one.
What is the main difference between a friend function and a derived class?
Now you have a basic understanding of C++ friend functions and inheritance. Practice these concepts in your own projects to gain a deeper understanding. Happy coding! š