Hello everyone,i was wondering if i could create a class object with specific elements and in the same time a struct object with the same elements and then to typecast convert the class object to struct.
#include<iostream>
using namespace std;
struct mrs
{
int a;
double b;
}mrs1;
class mrc
{
public:
int a;
double b;
}mrc1;
int main()
{
cout<<"size of mrs1:"<<sizeof(mrs1)<<endl;
cout<<"size of mrc1:"<<sizeof(mrc1)<<endl;
test.cpp: In function `int main()':
test.cpp:61: error: no matching function for call to `mrs::mrs(mrc&)'
test.cpp:29: note: candidates are: mrs::mrs()
test.cpp:29: note: mrs::mrs(const mrs&)
So it seems the above so called "type-cast" is actually interpreted by the C++ compiler you want to call the copy constructor or at least the class mrc constructor that take in struct mrs in it's argument.
class and struct are the same, it is just that by default (if you don't use private, public or protected), classes start out private and structs start out public.
All you have to do is define the function that converts from one to the other. It is usually both a constructor and an operator OtherClassOrStructName(OtherClassOrStructName& From)
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class A
{
public:
int Integer;
A(){}
A(constint& From){ Integer = From; }
~A(){}
};
struct B
{
long Long;
B(){}
B(cont long& From){ Long = From; }
B(const A& From){ Long = (long)From.Integer; } //Construct from A object
B operator B(const A& From){ B Temp (From); return(Temp); } //Allows Bobj = (B)Aobj;
~B(){}
};
Now, I haven't tested this, but it should work...I think...