Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call original function after it's been overridden in C++?

Tags:

c++

overriding

qt

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).

like image 282
jecjackal Avatar asked Jul 05 '11 19:07

jecjackal


People also ask

How do you call an overridden function?

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.

How do you call a derived function from base class?

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.

How can we access the base class implementation of an overridden method?

The overridden function of the base class can also be accessed by the derived class using the scope resolution operator (::).


2 Answers

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.

like image 106
Rycul Avatar answered Oct 05 '22 10:10

Rycul


void Sub::read(QDataStream &stream)
{
    Base::read(stream);
    // do Sub stuff here
}
like image 41
Useless Avatar answered Oct 05 '22 11:10

Useless