I have a class that looks like:
class A
{
public:
A();
void MethodThatWillNotBeInOtherStructure();
inline int getData() { return data; }
inline void setData(int data_) { data = data_; }
private:
int data;
}
and a structure like:
struct B
{
public:
inline int getData() { return data; }
inline void setData(int data_) { data = data_; }
private:
int data;
}
How can I copy an instance of A to B without individually setting the fields? I know I can as I have seen code that would take a void* of say A and pass it to a function expecting B and it work. My big question also, is how does this work? I suppose it has something to do with memcpy, but I don’t know how the memory layout for the structure and the class will be. For example, how do the functions that are in one but not the other not get in the way of the memcpy? Could someone explain this to me?
Update
Ok, let me explain. I am not saying I would ever do this in reusable code or that I would ever use it period. I still want to know how it works. Does a class have a different memory layout than a structure? How are the methods stored? Where is the data stored?
Thanks!
Copying two unrelated structures in to each other through
void *would work properly only if the two structures have the same memory layout. Otherwise the copying fails.Note that the objects of structure
AandBin your above code will have the same memory layout, since there member variables are identical.Copying through
void *works because one is just copying the actual memory occupied by one structure object in to memory occupied by another structure object.It is basically a bad idea to copy two unrelated structures in this way.
Consider the situation where you have pointers members inside your structure, a
memcpywould just cause a shallow copy of the pointer members, And if one of the object finishes its lifetime then eventually, the other object will be left with a dangling pointer member. That would eventually lead to an Undefined behavior(most likely a crash).How are the methods stored? Where is the data stored?
A normal function(non virtual) will be stored somewhere in the code section of the program. This location is the same for all instances of the class/structure and hence it is not a part of the memory allocation of each object of the class/structure.
In case of a virtual member function, the size of an class/structure does get affected due to presence of virtual functions, each object of the class/structure then has a special pointer called
vptrinside eachthis. Note that this is implementation detail of compilers and compilers may choose to implement it differently.