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; } 

live demo

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 this prvalue expression value address of object function called. type of this in member function of class x x*. if member function declared const, type of this const x*, if member function declared volatile, type of this volatile x*, , if member function declared const volatile, type of this const volatile x*. [ note: thus in const member function, object function called accessed through const access path. — end note ]

thus, interpreting above, in const member function this const returning non-const reference drops const qualifier , therefore compiler rightfully complains.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -