tags:

views:

135

answers:

1

Hi,

Just wondering why the syntax for virtual functions uses a const before the curly braces, as below:

  virtual void print(int chw, int dus) const;

Incidentally, the code doesnt seem to work without the const, which is interesting.. not sure why?

many thanks!

+5  A: 

The const in the function signature signifies a const member function - Anthony Williams gave a great answer on the implications.
Note that there is nothing special about virtual member functions functions in that regard, constness is a concept that applies to all non-static member functions.

As for why its not working without - you can't call non-const members on a const instance. E.g.:

class C {
public:
  void f1() {}
  void f2() const {}
};

void test() 
{
    const C c;
    c.f1(); // not allowed
    c.f2(); // allowed
}
Georg Fritzsche
this is great, many thanks!
oneAday
Good to hear :)
Georg Fritzsche
@gf: *constness* only applies to *non-static* member functions.
Jerry Coffin
Thanks, clarified that.
Georg Fritzsche
If it *compiles* without const, but doesn't *work* as expected (with is what "doesn't work" normally means), then the reason is most likely different. This `const` is a part of function signature. Const and non-const versions are different functions, which are overridden independently. For example, if you remove `const` from a virtual function in base class of the hierarchy and keep it in the derived classes, the functions in the derived classes will no longer override the function in the base class. The virtual functionality will fall apart and the code will no longer "work" as it used to.
AndreyT