Friday, 12 January 2007

When do we need to have definition for a "Pure Virtual Function"?

Any answers?

2 comments:

Anand Patil said...

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.

Prashanth Narayanaswamy said...

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();
} ///:~