Mat3o
Mat3o

Reputation: 5

Constructor initialized by function return

I cant follow why i cant initialize my class object in one line like below. Getting VS errors which are not simple for me:

"error:E0334 class "example" has no suitable copy constructor"

and

"C2440 'initializing': cannot convert from 'example' to 'example'"

Some code:

class example {
public:
    example() { R = 0.F; I = 0.F; };
    example(float, float);
    example(example &);
    example sum( float, float);
private:
    float R, I;
};

example::example(float s1, float s2):R(s1), I(s2) {}

example::example(example & ex2) {
    R = ex2.R;
    I = ex2.I;
}

example example::sum(float s1, float s2){
    example s;
    s.R = s1;
    s.I = s2;
    return s;
}

int main() {
    float a = 2;
    float b = 4;
    example object1(1,1);
    example object2(object1.sum(a,b));
    return 0;
}

Why initializing object2 like this:

example object2(object1.sum(a,b));

getting error, but something like this:

example object2;
object2 = (object1.sum(a,b));

pass without error, is it ok?

Upvotes: 0

Views: 161

Answers (2)

Wasting Time Master
Wasting Time Master

Reputation: 130

example object2(object1.sum(a,b));

this is not copy constructor, this is move constructor because argument is rvalue.

so, you can add move constructor explicitly like this.

class example {
public:
    example() { R = 0.F; I = 0.F; };
    example(float, float);
    example(example &);
    //move
    example(example &&);
    example sum( float, float);
private:
    float R, I;
};

example::example(float s1, float s2):R(s1), I(s2) {}

example::example(example & ex2) {
    R = ex2.R;
    I = ex2.I;
}

example::example(example && ex2){
    R = ex2.R;
    I = ex2.I;
}

example example::sum(float s1, float s2){
    example s;
    s.R = s1;
    s.I = s2;
    return s;
}

int main() {
    float a = 2;
    float b = 4;
    example object1(1,1);
    example object2(object1.sum(a,b));
    return 0;
}

and this

example object2;
object2 = (object1.sum(a,b));

is ok because,it will call copy assignment operator that compiler generate automatically (when you add move constructor like me, compiler will not generate copy assignment operator)

Upvotes: 0

O'Neil
O'Neil

Reputation: 3849

You're missing a const in the copy constructor

example(example const &);

Why initializing object2 like this:

example object2(object1.sum(a,b));

getting error

Because you can't get a non-const reference from the rvalue object1.sum(a,b).

but something like this:

example object2;
object2(object1.sum(a,b));

is ok?

This code is also wrong, the second line would require an operator ().

Upvotes: 1

Related Questions