0
Query on friend function
/* How to get out like below using single friend function? Note: Don't use public getter method. show value = 100 show value = 1000 */ #include <iostream> using namespace std; class T { public: virtual int show()=0; virtual ~T() {} }; class Test:public T { public: int i; Test(int _i):i(_i) { } int show() { return i; } friend void display(T& ); }; class Test2:public T { int i; public: Test2(int _i):i(_i) { } int show() { return i; } friend void display(T& ); }; void display(T& t) { cout<<"show value = "<<t.i<<endl; } int main(void) { Test t(100); display(t); Test2 t1(1000); display(t1); return 0; }
1 Respuesta
+ 1
First of all polymorphism doesn't work well with references, use pointers.
The best solution is to use your virtual show from a base pointer and forget the friend function.
Another way is to use CRTP but requires advanced knowledge and it's really complicated.
template <typename D>
Class Base{
friend void display<D>(Base*)
};
class Derived : public Base<Derived>{
int i;
};
template<typename T>
void display (Base* b){
cout<< static_cast<T*>(b)->i;
}
not tested, I suggest you to use your virtual function which is intended for that.