Extra semicolon in C ++

The following code compiled perfectly (no semicolon after each line). Why are semicolons not needed at the end of each line in a public section?

Note: adding a semicolon after each line is also great, so it seems that using a semicolon is optional.

template<typename T> class Accessor { public: explicit Accessor(const T& data) : value(data) {} Accessor& operator=(const T& data) { value = data; return *this; } Accessor& operator=(const Accessor& other) { this->value = other.value; return *this; } operator T() const { return value; } operator T&() { return value; } private: Accessor(const Accessor&); T value; }; 
+7
source share
5 answers

After defining the method, you do not need semicolons.

The reason that a semicolon is required after defining a class is that you can declare instances of the class immediately after the definition:

 class X { } x; //x is an object of type X 

For the method, this argument is obviously not executed, so the semicolon will be redundant (albeit legal).

+10
source

Your code is correct. This is how the language works; you don't need semicolons after the body of the method / function implementation.

If you add semicolons, nothing bad happens, because an empty statement with a semicolon is like no-op. For example, x += y;; is legal C ++.

+6
source

You do not need to put a semicolon after the closing parenthesis of a method declaration. In most codes, I have not seen such a semicolon.

+1
source

To be clear

 explicit Accessor(const T& data) : value(data) {} 

equivalently

 explicit Accessor(const T& data) :value(data) // initializer list { } 

This is the definition of a member function. Here, placing a semicolon at the end of a function signature makes it a declaration of a member function, which must be defined somewhere in the program outside the class, as shown below

 Accessor::Accessor(const T& data) { // some code } 

In addition, as follows from another answer, the end of the function body does not require a semicolon after the closing bracket (this requires the end of the class or structure definition), but adding one to the end will not create a difference, since this is considered no-op, and that is why you can add a semicolon at the end.

+1
source

Since C ++ rules do not require a semicolon after } in function / method declarations.

0
source

All Articles