Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must I put a semicolon at the end of class declaration in C++?

Tags:

c++

In a C++ class declaration:

class Thing {     ... }; 

why must I include the semicolon?

like image 474
Tarquila Avatar asked Nov 23 '09 14:11

Tarquila


People also ask

Why do we use semicolon after structure declaration in C?

Role of Semicolon (;) in C language: The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.

Why use a semicolon at the end of a class?

A semicolon after a close brace is mandatory if this is the end of a declaration. In case of braces, they have used in declarations of class, enum, struct, and initialization syntax. At the end of each of these statements, we need to put a semicolon.

Is semicolon mandatory in C?

Semicolon there is NOT optional.

Is it mandatory to have a semicolon at end of do while block on C?

A statement ends either with a block (delimited by curly braces), or with a semicolon. "do this while this" is a single statement, and can't end with a block (because it ends with the "while"), so it needs a semicolon just like any other statement.


2 Answers

The full syntax is, essentially,

class NAME { constituents } instances ;

where "constituents" is the sequence of class elements and methods, and "instances" is a comma-separated list of instances of the class (i.e., objects).

Example:

class FOO {   int bar;   int baz; } waldo; 

declares both the class FOO and an object waldo.

The instance sequence may be empty, in which case you would have just

class FOO {   int bar;   int baz; }; 

You have to put the semicolon there so the compiler will know whether you declared any instances or not.

This is a C compatibility thing.

like image 88
John R. Strohm Avatar answered Sep 28 '22 03:09

John R. Strohm


because you can optionally declare objects

class Thing {     ... }instanceOfThing; 

for historical reasons

like image 40
jk. Avatar answered Sep 28 '22 01:09

jk.