Azriel Elijay
Azriel Elijay

Reputation: 90

Semicolon(;) After Class Constructors or Destructors

I am currently maintaining and studying the language using a Legacy Source,I want to clear up some confusion on the use of semi-colons inside a class.

Here is the bit where confusion strikes me.

class Base
{
public:
  Base(int m_nVal = -1 ): nVal(m_nVal) {} // Confused here
  virtual ~Base() {} // Confused here
public:
  virtual void SomeMethod();
  virtual int  SomeMethod2();
protected: 
  int nVal;
};

class Derived : public Base
{
public:
  Derived(int m_nVal):nVal2(m_nVal) {}; // Confused here
  virtual ~Derived(){}; // Confused here
public:
  virtual void SomeMethod();
  virtual int SomeMethod2();
protected:/* Correction Here */
  int nVal2;
};

I have noticed that some of the class destructors/constructors have a Semi-colon after them and some of them don't, I do understand that the a semi-colon is a is a statement terminator. My question is does the Semi-colon after the constructors or destructor tells something specific to the compiler? or is it something that doesn't really matter.

Upvotes: 2

Views: 1196

Answers (2)

viraltaco_
viraltaco_

Reputation: 1190

does the Semi-colon after the constructors or destructor tells something specific to the compiler?

After (or before) a member function definition it does not.†
After (but not before) a member function declaration it is mandatory.
'Probably just an oversight.

†: Unless the definition has no body:

struct A { 
  A() = default; // Mandatory semicolon. Definition
  ~A() {}        // Accessory semicolon. Definition
  void foo();    // Mandatory semicolon. Declaration
};

Upvotes: 1

user4581301
user4581301

Reputation: 33932

The {} at the end of the function Base(int m_nVal = -1 ): nVal(m_nVal) {} means you have a complete definition of a function, not a mere declaration like virtual void SomeMethod();

Perhaps it would be more recognizable when spread out a bit better:

Base(int m_nVal = -1 ): 
    nVal(m_nVal) 
{
}

Now we can easily see we have the full function definition (with a member initializer list to boot) and functions never require a terminating semicolon.

Upvotes: 2

Related Questions