Your question is rather unclear. For example, I have no idea what you mean by " jump from one struct to another ..."
Also, as you define variables immediately after your struct definitions, it looks like they are intended for use in a single scope. This would makes it either (a) impossible to pass via a function, if defined at function scope, or (b) pointless, if defined at global scope.
Anyway...
As your two structs have exactly the same memory layout, as they have the same member types in the same order, it would be safe to reinterpret_cast from a pointer or reference of one type to the other.
But when a functions which takes a B& or B* reads the value of X, it will be the value set as V in the original A struct, etc. (see output + code below.)
Notes:
1. This cast "trick" has nothing to do with (subtype) polymorphism, which relies on inheritence and virtual functions (see link to Polymorphism provide by Computergeek01.)
2. You can use upcasting (converting a derived-class reference or pointer to a base-class) and downcasting (converting a base-class pointer or reference to a derived-class pointer) with structs which have an inheritence relationship. But this isn't (subtype) polymorphism, either.
3. I don't think this cast trick is a good thing to do, even though it's possible.
So...
Why do you need the two struct types in the first place? What problem are you trying to solve using this approach?? (A simplistic examples using single letter identifiers doesn't illustrate how this "trick" would be of any real use in real life code.)
Andy
PS C++ supports four type of polymorphism: when used alone, polymorphism is usually taken to mean subtype polymorphism, which uses inheritence and virtual functions and works at runtime. The others are parametric polymorphism (templating), ad-hoc polymorphism (overloading) and coercion polymorphism (type casting.)
variable a:
struct A:
V = 1
W = 2
X = 3
struct B:
X = 1
Y = 2
Z = 3
variable b:
struct A:
V = 4
W = 5
X = 6
struct B:
X = 4
Y = 5
Z = 6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <iostream>
using namespace std;
struct A
{ int V;
int W;
int X;
}; // Struct1;
struct B
{ int X;
int Y;
int Z;
}; // Struct2;
void dumpA(A& a) {
cout << "struct A:" << endl;
cout << " V = " << a.V << endl;
cout << " W = " << a.W << endl;
cout << " X = " << a.X << endl;
}
void dumpB(B& b) {
cout << "struct B:" << endl;
cout << " X = " << b.X << endl;
cout << " Y = " << b.Y << endl;
cout << " Z = " << b.Z << endl;
}
int main() {
A a = {1, 2, 3};
B b = {4, 5, 6};
cout << "variable a:" << endl;
cout << endl;
dumpA(a);
cout << endl;
dumpB(reinterpret_cast<B&>(a));
cout << endl;
cout << "variable b:" << endl;
cout << endl;
dumpA(reinterpret_cast<A&>(b));
cout << endl;
dumpB(b);
cout << endl;
cout << endl;
return 0;
}
|