Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual function const vs virtual function non-const

Tags:

c++

class Base
{
   public:
   virtual void func() const
   {
     cout<<"This is constant base "<<endl;
   }
};

class Derived : public Base
{
   public:
   virtual void func()
   {
     cout<<"This is non constant derived "<<endl;
   }
};


int main()
{
  Base *d = new Derived();
  d->func();
  delete d;

  return 0;
}

Why does the output prints "This is constant base". However if i remove const in the base version of func(), it prints "This is non constant derived"

d->func() should call the Derived version right, even when the Base func() is const right ?

like image 311
vamsi Avatar asked Feb 28 '12 19:02

vamsi


People also ask

Can a virtual function be const?

No, because virtual void func() is not an override for virtual void func() const .

What are virtual functions How do they differ from non-virtual member function?

Non-virtual member functions are resolved statically. That is, the member function is selected statically (at compile-time) based on the type of the pointer (or reference) to the object. In contrast, virtual member functions are resolved dynamically (at run-time).

What are pure virtual functions How are they different from normal functions?

A virtual function is a member function in a base class that can be redefined in a derived class. A pure virtual function is a member function in a base class whose declaration is provided in a base class and implemented in a derived class. The classes which are containing virtual functions are not abstract classes.

Can a const function call a non-const function?

const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.


1 Answers

 virtual void func() const  //in Base
 virtual void func()        //in Derived

const part is actually a part of the function signature, which means the derived class defines a new function rather than overriding the base class function. It is because their signatures don't match.

When you remove the const part, then their signature matches, and then compiler sees the derived class definition of func as overridden version of the base class function func, hence the derived class function is called if the runtime type of the object is Derived type. This behavior is called runtime polymorphism.

like image 145
Nawaz Avatar answered Oct 19 '22 03:10

Nawaz