Tuesday, July 14, 2009

In c++ why cant a friend function be declared as virtual?

A friend function can't be declared as virtual because it is NOT A MEMBER of the class. Rather its an outside member function which has been granted access to the members of the class.





You can get over this shortcoming by simply using an extra line of code. Here's an example:





class Base {


public:


friend void f(Base%26amp; b);


// ...


protected:


virtual void do_f();


// ...


};





inline void f(Base%26amp; b)


{


b.do_f();


}





class Derived : public Base {


public:


// ...


protected:


virtual void do_f(); // "Override" the behavior of f(Base%26amp; b)


// ...


};





void userCode(Base%26amp; b)


{


f(b);


}





The statement f(b) in userCode(Base%26amp;) will invoke b.do_f(), which is


virtual[20]. This means that Derived::do_f() will get control if b is actually


a object of class Derived. Note that Derived overrides the behavior of the


protected: virtual[20] member function do_f(); it does not have its own


variation of the friend function, f(Base%26amp;).


No comments:

Post a Comment