C++ Friend vs Inheritance šŸŽÆ

beginner
11 min

C++ Friend vs Inheritance šŸŽÆ

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++. šŸ“

Understanding C++ Friend šŸ’”

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.

cpp
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.

Understanding Inheritance šŸ’”

Inheritance is a mechanism where one class (child or derived class) acquires the properties and methods of another class (parent or base class).

cpp
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.

Friend vs Inheritance šŸ’”

  1. Access: Friends have special access to private and protected members, while inheritance allows accessing public, protected, and private members.

  2. Functionality: Friends are used to provide additional functionality to a class, while inheritance is used to create new classes from existing ones.

  3. 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.

Quiz

Quick Quiz
Question 1 of 1

What is the main difference between a friend function and a derived class?

Wrap Up āœ…

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! šŸš€