I have a user-defined class, say, MyClass
. Suppose its definition is as follows:
class MyClass
{
int a;
int *b;
Base *c;
};
where I have
class Base
{
int base_data;
public:
Base(int) { //implementation }
virtual void some_func() = 0;
}
and
class Derived1 : public Base
{
int derived_1;
public:
Derived1(int) { //implementation }
virtual void some_func() { //implementation }
}
and
class Derived2 : public Base
{
int derived_2;
public:
Derived2(int) { //implementation }
virtual void some_func() { //implementation }
}
I would like to send an object of this class to a QTcpsocket
. As per this answer, I could use a QDataStream
, and with the help of this, I have implemented as follows:
friend QDataStream& operator<<(QDataStream&, const MyClass&);
friend QDataStream& operator>>(QDataStream&, MyClass&);
in the class declaration, and am considering defining it as:
QDataStream& operator<<(QDataStream &stream, const MyClass &obj)
{
stream << obj.a;
stream << obj.(*b);
stream << obj.(*Base); // assume QDataStream has been overloaded for Base already
}
As I need to send the data, I am dereferencing the pointers and sending the data it points to.
Is this the correct way to do this?
If I do send it this way, I am not able to understand how I can recreate the object at the receiving end. I am considering:
QDataStream& operator<<(QDataStream &stream, MyClass &obj)
{
stream >> obj.a;
b = new int;
stream >> obj.(*b);
Base = new //what?
stream >> obj.(*Base); // assume QDataStream has been overloaded for Base already
}
For an int
pointer, I can create a new int
and assign the incoming value to it. But what about a pointer of type Base
? I don't know if it is of type Derived1
or Derived2
.
How do I handle this?
Is there any other way to send a class object, if there is no solution here?
Thank you.