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?
Summary. Virtual function calls are currently prohibited in constant expressions.
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. "
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.
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.
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.
There's no difference. A declaration's specifiers can usually be written in any order.
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.
No difference. You can apply modifiers in your favourite order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With