Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between const virtual and virtual const?

I saw that some function in C++ was declared as

virtual const int getNumber();

But what is the difference if the function is declared as the following?

const virtual int getNumber();

What is the difference between those two?

like image 831
ratzip Avatar asked Mar 23 '15 14:03

ratzip


People also ask

Can a const function be virtual?

Summary. Virtual function calls are currently prohibited in constant expressions.

Can we override const function in C++?

Quote from a c++ book: "It is a common mistake to hide a base class method when you intend to override it, by forgetting to include the keyword const. const is part of the signature, and leaving it off changes the signature, and thus hides the method rather than overrides it. "

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.

What is const function in C++?

Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.


4 Answers

As was already said, there is no difference. However, note that these two do differ:

virtual const int getNumber();
virtual       int getNumber() const;

In the first method, const refers to the returned value of type int.

In the second method, const refers to the object the method is called on; that is, this will have type T const * inside this method, - you will be able to call only const methods, modify only mutable fields and so on.

like image 57
lisyarus Avatar answered Sep 26 '22 01:09

lisyarus


There's no difference. A declaration's specifiers can usually be written in any order.

like image 40
Mike Seymour Avatar answered Sep 24 '22 01:09

Mike Seymour


There is no difference. If we look at the grammar summary for a decl-specifier-seq we can see that it's defined in a recursive manner:

decl-specifier:
     type-specifier

decl-specifier-seq:
     decl-specifier decl-specifier-seq

The only restriction is that const and volatile can be combined with any type specifier except themselves (no const const, volatile volatile, etc), there is no rule on the order in which you use them.

like image 21
user4703660 Avatar answered Sep 24 '22 01:09

user4703660


No difference. You can apply modifiers in your favourite order.

like image 26
jabujavi Avatar answered Sep 23 '22 01:09

jabujavi