In C++, the equivalent of final from Java is const. However, the use of const in C++ is slightly different from how final is used in Java.
In Java, final can be used for several purposes:
To make a variable immutable, meaning it cannot be changed once it has been assigned a value.
To declare a method that cannot be overridden in subclasses.
To mark an entire class as unable to be extended (similar to C++'s final class).
In C++, const is primarily used to make variables or references read-only:
const can be applied to variables to make them immutable.
const can be applied to member functions to indicate that they do not modify the object's data members.
const can be used in function parameters to declare that the function does not modify the argument.
To make a variable in C++ that is assigned during the constructor const, you can declare it as const and initialize it in the constructor's member initializer list. Here's an example:
cpp
#include <iostream>
class MyClass {
public:
explicit MyClass(const std::string& str) : str_{str} {
// The member initializer list initializes the const member
}
void print() const {
std::cout << "Value: " << str_ << std::endl;
}
private:
// The str_ member is const, so it cannot be changed once assigned
const std::string str_;
};
int main() {
const std::string initial_value = "Hello, World!";
MyClass my_class{initial_value};
// This will not compile because str_ is const
// my_class.str_ = "New Value";
my_class.print();
return 0;
}
In this example, str_ is a const member variable that is initialized in the constructor's member initializer list with the value passed to the constructor. Once initialized, str_ cannot be changed.
C++ does not have a direct equivalent to Java's final as a modifier for methods or classes that cannot be overridden. However, C++11 introduced the concept of final in the context of template template parameters, which is a different usage from Java's final.