I have just finished reading about pure virtual functions and I have a question
If we have a class that has just one pure virtual function and the other member functions are NOT pure virtual then does that make any sense. Because if a class has just one pure virtual function then it cannot be instantiated.
A pure virtual function is the same as a virtual function, it just has to be overridden for the class to be instantiable. Nothing else is affected, everything works the same way as before.
In this example is there a way to invoke sayHello method of class SpeakingPerson.
Since we are not allowed to make an object of class SpeakingPerson
void main()
{
EnglishPerson EP; // I can do this
SpeakingPerson SP; // but I cant do this since SpeakingPerson is abstract class . // So there is no way to print "And I say hello!"
}
So is it correct that since there is no way to print "And I say hello!" or
in other words since there is no way to invoke non virtual methods of abstract base class,
these non virtual member functions of base classes are redundant?????
What you are forgetting is that child classes inherit all of their parents' members. Inheritance forms an "is a" relationship.
- SpeakingPerson has a 'sayHello' function.
- EnglishPerson is a child of SpeakingPerson
-- this means that an EnglishPerson "is a" SpeakingPerson
Therefore... EnglishPerson also has a 'sayHello' function (it inherits it from SpeakingPerson)
1 2 3 4 5 6 7
int main() // <- always int with main... never void
{
EnglishPerson ep;
ep.sayHello(); // will call SpeakingPerson::sayHello
// and will print "And I say hello!"
}