Ctor not allowed return type

Having code:

struct B
{
    int* a;
    B(int value):a(new int(value))
    {   }
    B():a(nullptr){}
    B(const B&);
}

B::B(const B& pattern)
{

}

I'm getting err msg:
'Error 1 error C2533: 'B::{ctor}' : constructors not allowed a return type'

Any idea why?
P.S. I'm using VS 2010RC


Solution 1:

You're missing a semicolon after your struct definition.


The error is correct, constructors have no return type. Because you're missing a semicolon, that entire struct definition is seen as a return type for a function, as in:

// vvv return type vvv
struct { /* stuff */ } foo(void)
{
}

Add your semicolon:

struct B
{
    int* a;
    B(int value):a(new int(value))
    {   }
    B():a(nullptr){}
    B(const B&);
}; // end class definition

// ah, no return type
B::B(const B& pattern)
{

}

Solution 2:

You need a better compiler. With g++:

a.cpp:1: error: new types may not be defined in a return type
a.cpp:1: note: (perhaps a semicolon is missing after the definition of 'B')
a.cpp:5: error: return type specification for constructor invalid

The semicolon is needed because it terminates a possible list of instances of the struct:

struct B {
...
} x, y, z;

Creates three instances of B called x, y and z. This is part of C++'s C heritage, and will still be there in C++0x.