It’s possible to provide a definition for a pure virtual function in the base class. You’re still telling the compiler not to allow objects of that abstract base class, and the pure virtual functions must still be defined in derived classes in order to create objects. However, there may be a common piece of code that you want some or all of the derived class definitions to call rather than duplicating that code in every function.
I'm one of the millions of people who love technology. Fascinate to learn more and share with others. This blog is a great place to share few of my thoughts!
2 comments:
It’s possible to provide a definition for a pure virtual function in the
base class. You’re still telling the compiler not to allow objects of
that abstract base class, and the pure virtual functions must still be
defined in derived classes in order to create objects. However, there
may be a common piece of code that you want some or all of the
derived class definitions to call rather than duplicating that code in
every function.
Sample code snippet which uses pure virtual definition from "Thinking In C++" by Bruce Eckel
//: C15:PureVirtualDefinitions.cpp
// Pure virtual base definitions
class Pet {
public:
virtual void speak() const = 0;
virtual void eat() const = 0;
// Inline pure virtual definitions illegal:
//! virtual void sleep() const = 0 {}
};
// OK, not defined inline
void Pet::eat() const {
cout << "Pet::eat()" << endl;
}
void Pet::speak() const {
cout << "Pet::speak()" << endl;
}
class Dog : public Pet {
public:
// Use the common Pet code:
void speak() const { Pet::speak(); }
void eat() const { Pet::eat(); }
};
int main() {
Dog simba; // Richard's dog
simba.speak();
simba.eat();
} ///:~
Post a Comment