Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of allowing unnecessary semicolons in class definition [closed]

Tags:

c++

syntax

Consider following program:

#include <iostream>
struct Test
{
    int a;
    Test(int s) : a(s)
    { };        // Observe this semicolon
    int geta()
    {
        return a;
    }
};
int main()
{
    Test t(3);
    std::cout<<t.geta()<<'\n';
}

The program compiles fine even when I use -pedantic-errors option in both gcc & clang. (See live demo here & here.) I also don't get any error from compiler if I put semicolon at the end of geta() member function like following:

int geta()
{
   return a;
}; // This also compiles fine without any error or warnings in both g++ & clang

So, what is the purpose of allowing this unnecessary semicolon? Is there any use of this? Is it allowed explicitly by language standard?

like image 400
Destructor Avatar asked Mar 15 '23 04:03

Destructor


1 Answers

Semicolon (;) stands for empty declaration in c++. You can see Declarations

C++ class allows following things inside the braces:

  • list of access specifiers
  • member object
  • member function declarations and definitions
  • Reference:Class

    Thus going by above rule, empty declarations are allowed in c++. Which is why you have semicolon.

    like image 192
    Rishit Sanmukhani Avatar answered Apr 27 '23 15:04

    Rishit Sanmukhani