seda
seda

Reputation: 141

C++ assignment between different object types

I have a bunch of union classes (union_a, union_b, ...), all with same data members and different member functions. I want to be able to assign an object of any class to object of any other class, and use it in any ctor for init. A "work" union union_z is used as a mediator. Everything works fine in VC. In GC the last line gets "error: conversion from ‘union_a’ to non-scalar type ‘union_b’ requested".

Help me if you can, I'm...

union union_z{int m;};

union union_a{
    int  m;

    union_a(){}
    union_a(union_z x){m = x.m;}

    void operator=(union_z x){m = x.m;}
    operator union_z(){return *(union_z *)this;}
};

union union_b{
    int  m;

    union_b(){}
    union_b(union_z x){m = x.m;}

    void operator=(union_z x){m = x.m;}
    operator union_z(){return *(union_z *)this;}
};

union_a  a;
union_b  b(a);
b = a;
union_b  b1 = a; //error: conversion from ‘union_a’ to non-scalar type ‘union_b’ requested

Upvotes: 1

Views: 267

Answers (1)

James Kanze
James Kanze

Reputation: 153909

G++ is correct. The formal syntax of copy initialization is to convert the expression to the right of the = to the target type, then copy it. Which in this case supposes an implicit conversion from union_a to union_b. And there isn't one; the only conversion would require two user defined conversions, and two user defined conversions can never be used in an inplicit conversion.

See §8.5/16 and §13.3.1.4 (C++11, but the rules concering this haven't changed with regards to earlier versions).

Upvotes: 4

Related Questions