I serialize most of my classes with two functions, read() and write(). What I would like to do is have the read/write() function of the base class called from the subclasses so that I don't have to repeat the serialization code multiple times.
For example:
class Base
{
public:
base();
virtual read(QDataStream&);
virtual write(QDataStream&);
private:
int a, b, c, d;
}
class Sub : public Base
{
public:
Sub();
read(QDataStream&);
write(QDataStream&);
private:
int e, f, g, h;
}
So in this example, i would like the code to read/write a,b,c,d to come from Base. Sub would then call Base::read(QDataStream&) and then add whatever attributes are unique to Sub. This way I don't have to repeat the serialization code for each subclass (and possibly forget to do so).
Access Overridden Function in C++ To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.
The overridden function of the base class can also be accessed by the derived class using the scope resolution operator (::).
You can call base-class functions by prepending the function call with the base-class identifier, followed by the scope operator (::).
Like this:
class Base
{
public:
virtual void Function();
}
class Foo : public Base
{
public:
void Function();
void DoSomething();
}
void Foo::DoSomething()
{
Base::Function(); // Will call the base class' version of Function().
Function(); // Will call Foo's version of Function().
}
EDIT: Note removed by request.
void Sub::read(QDataStream &stream)
{
Base::read(stream);
// do Sub stuff here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With