is this valid c++?

S

Simon

Hi,

If I have the following :

struct sA
{
double A1;
double A2;
};

struct sB
{
double B1;
long B2;
};

struct sC : sA, sB
{
double C1;
double C2;
};

//
// main app
sC myC = ... // set some values;
sA myA = (sA)myC;
sB myB = (sB)myB;

//
//

When I do it on my compiler, VS2009 it works.

In other word the value of myA has the values from myC simply by casting.
And the same for myB getting the right values from myC by casting.

But I doubt there are any rules in the standard that say that when you cast
like that you must copy the right values.

If this is not 'standard' what would be the better way of getting sA and sB
from sC

Many thanks

Simon
 
P

peter koch

Hi,

If I have the following :

struct sA
{
  double A1;
  double A2;

};

struct sB
{
  double B1;
  long B2;

};

struct sC :  sA, sB
{
  double C1;
  double C2;

};

//
// main app
sC myC = ... // set some values;
sA myA = (sA)myC;
sB myB = (sB)myB;

//
//

When I do it on my compiler, VS2009 it works.

In other word the value of myA has the values from myC simply by casting.
And the same for myB getting the right values from myC by casting.

You don't need the cast - remove it.
But I doubt there are any rules in the standard that say that when you cast
like that you must copy the right values.

There is not, but there are good rules that tell you to avoid casts
and - equally important - "never" to use C-style casts. C++ has
defined safer and better casts - use those instead.

/Peter
 
J

James Kanze

If I have the following :
struct sA
{
double A1;
double A2;
};
struct sB
{
double B1;
long B2;
};
struct sC : sA, sB
{
double C1;
double C2;
};
//
// main app
sC myC = ... // set some values;
sA myA = (sA)myC;
sB myB = (sB)myB;

When I do it on my compiler, VS2009 it works.

One would hope so.
In other word the value of myA has the values from myC simply
by casting. And the same for myB getting the right values
from myC by casting.

You don't even need the casts. An sC isA sA and an sB.
But I doubt there are any rules in the standard that say that
when you cast like that you must copy the right values.

Of course there are. It's more or less one of the basics of
inheritance.
 
S

Simon

Except that the last line invokes undefined behavior by assigning the
uninitialized myB to itself.

oops, that was a typo
it should say

....
sC myC = ... // set some values;
sA myA = (sA)myC;
sB myB = (sB)myC;

Thanks

Simon
 

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

Forum statistics

Threads
474,264
Messages
2,571,065
Members
48,770
Latest member
ElysaD

Latest Threads

Top