Covariant virtual function in C ++

I tried the following program, but the compiler shows an 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&' from expression of type 'const Base'
[Error] invalid initialization of reference of type 'Derived&' from expression of type 'const Derived'

Why am I getting these errors?
But when I write the following in both classes, the function program works fine.

return (Base&)*this;      // write this line in Base class function
return (Derived&)*this    // write this line in Derived class function

What is the meaning of the above statements?
Please help me.

+4
source share
3 answers

Decision:

In your member functions fun(i.e. for Base::funand Derived::fun) you need to either reset the constfunction qualifier :

virtual Base& fun() 
{
  std::cout<<"fun() in Base\n";
  return *this;
}

or return a const reference for a class object Base.

virtual const Base& fun() const
{
  std::cout<<"fun() in Base\n";
  return *this;
}

Live Demo

, , Base, , .

:

ยง 9.3.2 this [class.this]:

(9.3) - this prvalue, , . this - a class X X*. - โ€‹โ€‹const, this const X*,, โ€‹โ€‹ volatile, this volatile X*, - โ€‹โ€‹const volatile, this const volatile X*. [: const, , , const. - ]

, const member this const, const, , , .

+8

const

virtual Base& fun() const 

... this const . ,

return *this;

... , Base&, const.

const , this const, const Base&.

+4

const , , " , ". const , , " ". const - (), , " - , ".

- , const . , .

  • , const.
  • , const.
  • , const, , , , const.
  • - const , โ€‹โ€‹ const.

, โ€‹โ€‹ const , . const , , . const.

, - โ€‹โ€‹ const , , . โ€‹โ€‹ const, , .

, - , , ( ), const . , , const . , - , , const .

const -, , , const . , - const, const, . const.

, .

  • , .
  • const ( const ).
  • const .
+1

Source: https://habr.com/ru/post/1546092/


All Articles