classes in unions?

U

uralmutlu

Hi,

I was wandering if I can have classes in unions?

I basically have source code in a format very similar to:

union example {
ClassA variable1;
ClassB variable2;
};

class AnotherClass {
.....
example SomeName;
.....

};

However, the compiler (gcc) tells me constructors aren't allowed in
unions.

I have a very large program written for eg ClassA, and I am adding a
second class, eg ClassB, to it. I came to this particular code, and I
thought unions would be an easy solution, but it looks like I will have
to make other changes.

I thought since classes are types they would be allowed in unions.

so no classes in unions?

regrads
 
I

Ian Collins

Hi,

I was wandering if I can have classes in unions?

I basically have source code in a format very similar to:

union example {
ClassA variable1;
ClassB variable2;
};

class AnotherClass {
.....
example SomeName;
.....

};

However, the compiler (gcc) tells me constructors aren't allowed in
unions.

I have a very large program written for eg ClassA, and I am adding a
second class, eg ClassB, to it. I came to this particular code, and I
thought unions would be an easy solution, but it looks like I will have
to make other changes.

I thought since classes are types they would be allowed in unions.

so no classes in unions?
Think about it - which constructor initialises the object?

Unions are rare in C++ (compared to C), C++ offers more appropriate
solutions. Unions are often used as a poor man's polymorphism in C.
 
J

Jim Langston

Hi,

I was wandering if I can have classes in unions?

I basically have source code in a format very similar to:

union example {
ClassA variable1;
ClassB variable2;
};

class AnotherClass {
....
example SomeName;
....

};

However, the compiler (gcc) tells me constructors aren't allowed in
unions.

I have a very large program written for eg ClassA, and I am adding a
second class, eg ClassB, to it. I came to this particular code, and I
thought unions would be an easy solution, but it looks like I will have
to make other changes.

I thought since classes are types they would be allowed in unions.

so no classes in unions?

regrads

Instead of a union, I think polymorphism would work better for you.
 

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

No members online now.

Forum statistics

Threads
474,172
Messages
2,570,933
Members
47,472
Latest member
blackwatermelon

Latest Threads

Top