Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pure virtual const member function

Tags:

c++

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; 
like image 934
Chin Avatar asked Nov 07 '12 18:11

Chin


People also ask

Can pure virtual functions be const?

From my book: "Because you have declared Volume() as const, its implementation in any derived class must also be const. Remember that const and non-const varieties of a function with the same name and parameter list are different functions.

How do you declare a pure virtual function as const in C++?

To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. Show activity on this post. Hence, the = 0 must come after the const . I prefer this answer, since it refers to the c++ specification, instead of the microsoft one.

What is a pure virtual member function?

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.

Can a member function be virtual?

A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.


1 Answers

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; 
like image 89
raina77ow Avatar answered Oct 25 '22 13:10

raina77ow