Reputation: 610
I'm learning about object oriented C++ and had a question about virtual/pure virtual and multi-level inheritance.
Lets say I have simple code like this:
class Shape
{
virtual int getWidth() = 0;
};
class Rectangle: public Shape
{
private:
int length, width;
public:
Rectangle(_length, _width) { length = _length; width = _width }
int getWidth() { return width }
};
class Square: public Rectangle
{
private:
int length;
public:
Square(int _length):Rectangle(_length, _length) { length = _length };
int getWidth() { return length+1 }; //arbitarily add 1 to distinguish
};
int main()
{
Rectangle* r = new Square(5);
std::cout << r->getWidth << std::endl; //prints 6 instead of 5? It's as if rectangles getWidth is virtual
}
My understanding is that polymorphism will use the function of the "Base" class unless getWidth is specified as virtual. By this I mean that the final call of r->getArea should be using the Rectangle's getArea instead of Square's getArea.
In this case, I notice if I remove the pure virtual declaration in Shape, we get the behavior I just described. Does having a pure virtual function in a base class automatically make all definitions of that function virtual?
Upvotes: 2
Views: 683
Reputation: 26800
You don't need to have a pure virtual function to get polymorphic behavior. Normal virtual function can also accomplish it.
Yes, specifying a function as virtual
in a class means that it remains virtual
in all the classes derived from it.
From C++11 onwards, there is also the override
specifier:
In a member function declaration or definition, override
ensures that the function is virtual
and is overriding a virtual function from a base class.
Upvotes: 4
Reputation: 409136
virtual
is inherited. If you make a parent function virtual
then it will keep on being virtual
in all child-classes.
Upvotes: 4