কম্পিউটার টিউটোরিয়াল

C++-এ ইনহেরিটেন্স ও ফ্রেন্ডশিপ: ফ্রেন্ডশিপ ইনহেরিট হয় না

C++-এ ফ্রেন্ডশিপ (friendship) ইনহেরিটেবল নয়। অর্থাৎ, যদি বেস ক্লাসের কোনো ফ্রেন্ড ফাংশন/ক্লাস থাকে, তবে ডেরাইভড ক্লাস আটোমেটিক্যালি সেটির ফ্রেন্ড হয় না।

উদাহরণ

#include <iostream>
using namespace std;

class MyBaseClass {
protected:
    int x;
public:
    MyBaseClass() { x = 20; }
    friend void display(); // display() হলো বেসের ফ্রেন্ড
};

class MyDerivedClass : public MyBaseClass {
private:
    int y;
public:
    MyDerivedClass() { x = 40; }
};

void display() {
    MyDerivedClass derived;
    cout << "Base x: " << derived.x << endl; // OK: বেসের প্রটেক্টেড অ্যাকসেস
    cout << "Derived y: " << derived.y << endl; // ERROR: y প্রাইভেট, display() ডেরাইভডের ফ্রেন্ড নয়
}

int main() {
    display();
    return 0;
}

আউটপুট (কম্পাইল এরর)

[Error] 'int MyDerivedClass::y' is private within this context

ব্যাখ্যা

  • display() হলো MyBaseClass-এর ফ্রেন্ড, তাই এটি বেসের protected মেম্বার x অ্যাকসেস করতে পারে।
  • কিন্তু MyDerivedClass-এর প্রাইভেট মেম্বার y অ্যাকসেস করতে পারে না, কারণ ফ্রেন্ডশিপ ইনহেরিট হয় না।

সমাধান: ডেরাইভড ক্লাসে আলাদা friend void display(); ডিক্লেয়ার করুন, অথবা পাবলিক গেটার ফাংশন দিন।

  1. C++-এ মাল্টিপল ইনহেরিট্যান্স

  2. C++-এ লোকাল ক্লাস

  3. C++-এ ক্লাস এবং অবজেক্ট

  4. C++-এ ফ্রেন্ড ক্লাস এবং ফাংশন