33

I have always wondered why we code

virtual void MyFunction() = 0; 

and not

pure virtual void MyFunction();

Is there a reference for the basis of this decision?

Peter Mortensen
  • 1,050
  • 2
  • 12
  • 14

1 Answers1

73

From The Design and Evolution of C++ - Bjarne Stroustrup - Addison-Wesley (ISBN 0-201-54330-3) - chapter 13.2.3:

The curious = 0 syntax was chosen over the obvious alternative of introducing a new keyword pure or abstract because at the time I saw no chance of getting a new keyword accepted. Had I suggested pure, Release 2.0 would have shipped without abstract classes. Given a choice between a nicer syntax and abstract classes, I chose abstract classes. Rather than risking delay and incurring the certain fights over pure, I used the tradition C and C++ convention of using 0 to represent not there.

Anyway looking at the C++ standard (§ 9.2 - Class members) = 0 is called pure-specifier.

manlio
  • 4,166
  • 3
  • 23
  • 35
  • 11
    that's cool. Reminds me of why PHP has so many different ugly function names: because the first interpreter used strlen as hash function and distribution should be good (http://www.i-programmer.info/news/98-languages/6758-the-reason-for-the-weird-php-function-names.html) – Aitch May 20 '15 at 09:21
  • 10
    The introduction of context-sensitive keywords in C++11 has reduces the damage that adding keywords causes. It should be possible to make `pure` a contextual keyword you put at the end of a function definition, so `virtual void MyFunction() pure` instead of `= 0`, to go along with `final` and `override`. – Yakk May 20 '15 at 13:56
  • 23
    As an aside, nearly everywhere a "pure function" is understood to be a function whose output only depends on its input, and which has no side-effects. – Deduplicator May 20 '15 at 15:33
  • 2
    Pretty much any question of "why does C++ do X?" can be answered by that book. It should be required reading for any serious C++ programmer. – Gort the Robot May 20 '15 at 15:39
  • 1
    Where are these called pure, anyway? Both C# and Java use "abstract" as the keyword here. – Random832 May 20 '15 at 19:05
  • 1
    @Aitch, yup. It substituted the (solved) problem of how to hash strings with the (very hard) problems of naming things. – Paul Draper May 20 '15 at 19:18
  • 4
    @Random832 it's "pure virtual" (as in "100% virtual and 0% anything else"), not just "pure". – user253751 May 20 '15 at 19:36
  • @immibis Interestingly the standard still uses the term "abstract class" to refer to a class with at least one pure virtual member function; it uses BOTH terms. Also, are you the "immibis" in "immibis's microblocks"? – chbaker0 May 20 '15 at 22:29
  • @chbaker0 Classes can't be virtual, so it wouldn't make sense to call them pure virtual classes. – user253751 May 20 '15 at 22:30
  • @chbaker0 Also yes. – user253751 May 20 '15 at 22:31