Can i convert from class to struct or the oposite?

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;

mrc1.a=2;
mrc1.b=3;

mrs1=struct(mrc1);


return 0;
}

I hope you could understand what i mean.thanks
Above does not compile in g++

So I play around and say

 
mrs1 = (struct mrs)(mrc1);


Above g++ give below error.

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.

You raise an interesting question though.
That's not what you want to do.

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(const int& 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...
Last edited on
got it,thanks
Topic archived. No new replies allowed.