Search code examples
c++inheritancevirtual

why does the derived class could call the member function in the base class?


my question is that, I have three class, A is abstract class. B derived from A, then C derived from B.

I just list the function which I have question.

class A{
public:virtual void storedata(int a, int b, int c, int d)=0;
}

B.h
class B: public A{
public:virtual void storedata(int a, int b, int c, int d);
}
B.cpp
void storedata(int a, int b, int c, int d)
{ do something }

C.h
class C: public B{
public:virtual void storedata(int a, int b, int c, int d); 
}

C.cpp
void storedata(int a, int b, int c, int d)
{
    B::storedata(int a, int b, int c, int d);
}

Why could the derived class C could call the B::storedata in C.cpp?


Solution

  • Why shouldn't it be able to? The point of overriding a virtual function is to allow you to customise the behaviour of objects of the derived type, but sometimes the desired behaviour consists of performing the processing that a base did, possibly conditionally or with some pre- or post- action. Indeed, you can provide implementations of pure virtual functions, and that's mainly useful so that derived classes can conveniently call the abstract base class's implementation when it happens to suit them. In this case, the override is useless because it only does exactly what the B version does, but in general it's potentially useful to allow the B version to be called.