First, I am coming from the Java community, and still a learner in C++.
Please have a look at the following classes
The second picture shows a sub class of the class "GameObject". It also has a Display()
method. There are 5 sub classes of the class GameObject, and they all have this Display()
method. So, is this display method in GameObject
is a virtual one?
I think it is not abstract virtual (100% virtual) because the Display()
in GameObject
displays some texts in GameObject.cpp
Anyway, I am not quite sure. Please help!
In C++, virtual functions are virtual if and only if the have been explicitly declared virtual in a base class or the class itself. Since GameObject seems to have no base class, GameObject::Display()
hast to be declared virtual, if displaying a GameObject reference (or pointer) should behave according to actual (i.e. runtime) type of the object behind that reference.
Having a function body in GameObject.cpp does not mean the function is not pure virtual (the C++ equivalent for java's abstract). You can make the function pure virtual by adding a = 0
to its declaration. Nevertheless you can provide a implementation for pure virtual methods, e.g. to have a default implementation that you explicitly call in derived classes implementing the method:
class GameObject {
//...
public:
virtual void Display() = 0;
};
//GameObject.cpp
void GameObject::Display() {
/* do something */
}
//DerivedGO.h
class DerivedGO : public GameObject {
public:
// virtual can be left out here, since it's declared virtual in the base class
virtual void Display() {
prepDisplay(); // do some preparation
GameObject::Display(); //call the original/default implementation
}
};
However be aware that making a function pure virtual means making the containing class abstract and every derived class as well that does not override all pure virtual functions from its base classes.