Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "= 0;" do when declaring pure virtual functions in C++? [duplicate]

Tags:

c++

virtual

Possible Duplicate:
Why pure virtual function is initialized by 0?

I know that, in order to declare a pure virtual function you need to use "= 0;" syntax, like so:

class Foo  
{
protected:
    Foo();
    virtual int getValue() = 0;
};

My question is, what exactly (in the internal workings of the compiler) does the "= 0;" syntax do? Does it actually set the function pointer equal to zero? Does it serve as nothing more than a statement of intent, like the "abstract" reserved word in Java and C#, and if so, why not add a reserved word such as "abstract" to the language rather than using such arcane syntax?

like image 345
Sepulchritude Avatar asked Feb 14 '12 15:02

Sepulchritude


People also ask

What does 0 indicate in a function declaration in a class?

It is a pure virtual function. The =0 is just the syntax used to indicate that it is a pure virtual function. Presence of a Pure virtual function in a class makes the class an Abstract class.

Why is a pure virtual function initialized by 0?

It's just a syntax, nothing more than that for saying that “the function is pure virtual”. 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 declaration.

What does a virtual function 0 mean?

The = 0 after a virtual function means that "this is pure virtual function, it must be implemented in the derived function". As in your example, it's still possible to implement the function. It has no other meaning as such - and you can't use other numbers, addresses or anything else.

How pure virtual function is declared?

A pure virtual function is declared by assigning 0 in the declaration. These are the concepts of Run-time polymorphism.


1 Answers

It declares a 'pure virtual' function. The = 0 is basically like another 'pure' keyword. This question is related to yours: Why is a pure virtual function initialized by 0?

A pure virtual function has no body at all and must be defined by any classes which inherit it: http://www.learncpp.com/cpp-tutorial/126-pure-virtual-functions-abstract-base-classes-and-interface-classes/

like image 172
David Avatar answered Sep 21 '22 13:09

David