UnworthyToast
UnworthyToast

Reputation: 835

Class/member function error

I have this snippet of code here:

class physics_vector
{ 
public:
    double direction, magnitude;
    int dir_mag(double dir, double mag) :direction(dir), 
        magnitude(dir) {return 0; };
};

int dir_mag(double dir, double mag)
{
    cout << "Direction: " << dir << '\n';
    cout << "Magnitude: " << mag << '\n';
    return 0;
}

Whenever I try to compile I get the error,

13:39: error: only constructors take member initializers

Any help please?

Upvotes: 3

Views: 16142

Answers (2)

HadeS
HadeS

Reputation: 2038

You cannot use initializer list in functions.Its not a valid operation in C++. You can use Initializer list only with Constructor. Compiler is giving very clear error.

Upvotes: 1

Peter R
Peter R

Reputation: 2985

This function:

int dir_mag(double dir, double mag) :direction(dir), magnitude(dir)
{return 0; };

is using an initializer list (:direction(dir), magnitude(dir)) and that's only allowed for constructors. If you had planned to make this a constructor your class should look like this:

class physics_vector
{ 
public:
    double direction, magnitude;
    physics_vector(double dir, double mag) :direction(dir), 
        magnitude(dir) {};
};

And that will compile. Note that you are not allowed a return value from a constructor, nor do they have return types.

Upvotes: 6

Related Questions