I was reading about Virtual Functions from the book "The C++ Programming Langauge" by Bjarne Stroustrup, and encountered the following code snippet:-
class A {
//...
protected:
int someOtherField;
//...
public:
virtual void print() const;
//...
};
class B : public A {
//...
public:
void print() const;
//...
};
void B::print() const {
A::print();
cout<<A::someOtherField;
//...
}
It is written in the book that
"Calling a function using the scope resolution operator(::) as done in B::print() ensures that virtual mechanism is not used. Otherwise, B::print() would suffer infinite recursion."
I do not understand why this is the case, since, a call to the base class function correctly and explicitly tells that we are calling A::print() and not anything else. Why this may lead to infinite recursion?
Edit - I misplaced the keyword "virtual", I am extremely sorry for that, but still exploring this question also, What would happen if the following code was there?
- @HTNW's comment provides proper insights
class A {
//...
void print() const;
//...
}
class B : public A {
//...
virtual void print() const;
//...
}