51

How can I declare a pure virtual member function that is also const? Can I do it like this?

virtual void print() = 0 const;

or like this?

virtual const void print() = 0;
Chin
  • 19,717
  • 37
  • 107
  • 164

4 Answers4

69

From Microsoft Docs:

To declare a constant member function, place the const keyword after the closing parenthesis of the argument list.

So it should be:

virtual void print() const = 0;
raina77ow
  • 103,633
  • 15
  • 192
  • 229
21

Only the virtual void print() const = 0 form is acceptable. Take a look at the grammar specification in C++03 §9/2:

member-declarator:
    declarator pure-specifieropt
    declarator constant-initializeropt
    identifieropt : constant-expression

pure-specifier:
    = 0

The const is part of the declarator -- it's the cv-qualifier-seqopt in the direct-declarator (§8/4):

declarator:
    direct-declarator
    ptr-operator *declarator*

direct-declarator:
    declarator-id
    direct-declarator ( parameter-declaration-clause ) cv-qualifier-seqopt exception-specificationopt
    direct-declarator [ constant-expressionopt ]
    ( declarator )

Hence, the = 0 must come after the const.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
6

Of course you can. The correct syntax is:

virtual void print() const = 0;
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
4

Try this:-

 virtual void print()  const = 0;
Martin York
  • 257,169
  • 86
  • 333
  • 562
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331