Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ : code explanation for method prototype with const = 0

Tags:

c++

virtual

I hava a class declaration with a piece of code that I do not understand :

class Weapon {   public:     virtual void attack() const = 0; }; 

What does the const = 0 part means ?

like image 585
Jérémy Pouyet Avatar asked Jan 17 '14 14:01

Jérémy Pouyet


People also ask

What does Const 0 do in C++?

class Shape { public: virtual void draw() const = 0; // = 0 means it is "pure virtual" ... }; This pure virtual function makes Shape an ABC. If you want, you can think of the "= 0;" syntax as if the code were at the NULL pointer.

How do you define a pure virtual function in C++?

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.

What is virtual void in C++?

A C++ virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword. It is used to tell the compiler to perform dynamic linkage or late binding on the function.


1 Answers

This is a pure virtual method (=0) which is not supposed to change the data of the class (const). You should provide an implementation in one of the classes deriving from Weapon! See this: Difference between a virtual function and a pure virtual function

You are expected to derive from the Weapon (can be considered interface) concrete classes, such as Axe , Shotgun, etc ... where you will provide the attack() method.

like image 140
Ferenc Deak Avatar answered Sep 20 '22 19:09

Ferenc Deak