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(); ডিক্লেয়ার করুন, অথবা পাবলিক গেটার ফাংশন দিন।