Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual functions in C++11

In C++98, the null pointer was represented by the literal 0 (or in fact any constant expression whose value was zero). In C++11, we prefer nullptr instead. But this doesn't work for pure virtual functions:

struct X {     virtual void foo() = nullptr; }; 

Why does this not work? Would it not make total sense? Is this simply an oversight? Will it be fixed?

like image 655
fredoverflow Avatar asked Dec 31 '13 17:12

fredoverflow


People also ask

What is a pure virtual function in C?

A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly.

What is virtual and pure virtual function in C?

A virtual function is a member function of base class which can be redefined by derived class. A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract.

What is the use of pure virtual function?

A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in the declaration. An abstract class is a class in C++ which have at least one pure virtual function.

How do you write a pure virtual function?

A pure virtual function doesn't have the function body and it must end with = 0 . For example, class Shape { public: // creating a pure virtual function virtual void calculateArea() = 0; }; Note: The = 0 syntax doesn't mean we are assigning 0 to the function.


2 Answers

Because the syntax says 0, not expression or some other non-terminal matching nullptr.

For all the time only 0 has worked. Even 0L would be ill-formed because it does not match the syntax.

Edit

Clang allows = 0x0, = 0b0 and = 00 (31.12.2013). That is incorrect and should be fixed in the compiler, of course.

like image 154
Johannes Schaub - litb Avatar answered Oct 08 '22 23:10

Johannes Schaub - litb


The = 0 notation for virtual functions wasn't literally "assign null" but rather a special notation which is actually deceptive: a pure virtual function can also be implemented.

With various context keywords it would make more sense to allow abstract rather than = nullptr and have abstract be a context keyword.

like image 26
Dietmar Kühl Avatar answered Oct 08 '22 22:10

Dietmar Kühl