constructor with/without semicolon

T

thomas

for the following code, line L can also be written as
A(int i):data(i){}; // L1
A(int i):data(i){} // L2

As I know, L2 works because it's a function;
but how can L1 work? It seems to be a declaration.

---code---
#include<iostream>
using namespace std;

class A{
int data;
public:
A(int i):data(i){} // L
void B(){
cout<<data<<endl;
}
};

int main(){
A(3).B();
}

---code--
 
I

Ian Collins

thomas said:
for the following code, line L can also be written as
A(int i):data(i){}; // L1
A(int i):data(i){} // L2

As I know, L2 works because it's a function;
but how can L1 work? It seems to be a declaration.
No, the semicolon is simply superfluous.
 
M

Marcel Müller

thomas said:
for the following code, line L can also be written as
A(int i):data(i){}; // L1
A(int i):data(i){} // L2

As I know, L2 works because it's a function;
but how can L1 work? It seems to be a declaration.

A constuctor/destructor is a function too. A Function without a return
value of course. And like outside a class definition a function
implementation requires no semicolon. Compare it to:

A::A(int i)
: data(i)
{ // empty
}
^ Here is usually no semicolon too.


Marcel
 
J

James Kanze

thomas schrieb:
A constuctor/destructor is a function too. A Function without a return
value of course. And like outside a class definition a function
implementation requires no semicolon. Compare it to:
A::A(int i)
: data(i)
{ // empty}
^ Here is usually no semicolon too.

With a slight difference: a semicolon after a function
definition outside of the class is illegal. One after a
function definition inside the class is explicitly permitted.
(I think most compilers allow one after the function definition
outside the class as well, as an extension. Logically, it
creates an empty statement, and the only reasons for forbidding
empty statements at namespace scope are historical.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top