49

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
  • 18,166
  • 35
  • 100
  • 154

4 Answers4

67

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
  • 99,006
  • 14
  • 190
  • 222
20

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
  • 375,615
  • 96
  • 501
  • 581
6

Of course you can. The correct syntax is:

virtual void print() const = 0;
πάντα ῥεῖ
  • 85,314
  • 13
  • 111
  • 183
4

Try this:-

 virtual void print()  const = 0;
Martin York
  • 246,832
  • 83
  • 321
  • 542
Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319