Final Keyword

I was doing some class research and I came across this keyword final. It's the first time i've ever seen it, the description said it was used when you explicitly do not want classes to be inheritable. So my question is when should i use it? should I put it after every class I make if it wont be inherited from, or only use it in special cases, and if so, what are some special use cases?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Bank final
{
public:
	Bank() = default;
	~Bank() = default;

	void WithdrawlMoney();
	void DepositMoney();
	void EnterPinNumber();
	float ShowAccountBalance() const;
	void SetAccountBalance();
	void CreateAccount();

private:
	unsigned short int pin = 0;
	int accountBalance = 0;
	int playerBalance = 0;
	string name = "default";
};
final is not a keyword; it is a specifier. It has a special meaning (defined by the standard) only when it is applied to a class (appears immediately after the name of the class) or a virtual member function (appears immediately after the declarator of the function).


> when should i use it? should I put it after every class I make if it wont be inherited from.

Use it for a class that is specifically designed not to be inherited from.
In general, use it if and only if inheriting from the class, no matter how the inheritance is done, would lead to a serious logical error; ie. do not apply the final specifier merely because a class is not specifically designed for inheritance.

For instance, the vast majority of classes in the standard library are not specifically designed to be inherited from; yet the standard specifies: "All types specified in the C ++ standard library shall be non-final types unless otherwise specified." Even the numeric_limits specializations like std::numeric_limits<char> are not marked as final.
Topic archived. No new replies allowed.