Question

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?

Was it helpful?

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.

OTHER TIPS

Function storedata of class C may not call function storedata of class B because the function storedata in class B declared as having access control private.

So the compiler shall issue an error.

it could be called by class C if it would be declared in class B having either public or protected access control. It could be called because in function storedata of class C the call specifies qualified name that refers to function storedata in class B.

Functions declared in base class are also members of derived class. If the derived class declares a function with the same name as a function in the base class then the function in the derived class hides the function in the base class. You can call the function of the base class in some method of the derived class by means of using qualified name that refers to the function in the base class. And it is not important whether the function is virtual or not.

EDIT: I see you have read my post and changed the private access control to the public access control.:)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top