covariant virtual function in C++ -
i tried following program, compiler shows error.
#include <iostream> class base { public: virtual base& fun() const { std::cout<<"fun() in base\n"; return *this; } }; class derived : public base { public: derived& fun() const { std::cout<<"fun() in derived\n"; return *this; } }; int main() { base* p=new derived(); p->fun(); delete p; return 0; } compiler errors:
[error] invalid initialization of reference of type 'base&' expression of type 'const base' [error] invalid initialization of reference of type 'derived&' expression of type 'const derived' why getting these errors?
when write following in both class' function program works fine.
return (base&)*this; // write line in base class function return (derived&)*this // write line in derived class function what meaning of above 2 statements?
please me.
solution:
in fun member functions (i.e., both base::fun , derived::fun) have either drop const qualifier of function:
virtual base& fun() { std::cout<<"fun() in base\n"; return *this; } or return const reference base class object.
virtual const base& fun() const { std::cout<<"fun() in base\n"; return *this; } also have define virtual destructor @ least base class ensure destructors evoked in correct order.
explanation:
according standard § 9.3.2 this pointer [class.this]:
in body of non-static (9.3) member function, keyword
thisprvalue expression value address of object function called. type ofthisin member function ofclass xx*. if member function declaredconst, type ofthisconst x*, if member function declaredvolatile, type ofthisvolatile x*, , if member function declaredconst volatile, type ofthisconst volatile x*. [ note: thus inconstmember function, object function called accessed throughconstaccess path. — end note ]
thus, interpreting above, in const member function this const returning non-const reference drops const qualifier , therefore compiler rightfully complains.
Comments
Post a Comment