C++ pure virtual functions
Created By: chatGPT
Pure Virtual Functions are a key feature of C++ that enable you to define abstract classes. A pure virtual function is a function declared in a base class that has no definition relative to that class. It forces derived classes to provide an implementation for the function. This is particularly useful in designing interfaces and establishing a contract that derived classes must follow.
class Base {
public:
virtual void show() = 0; // Pure virtual function
};
class Derived : public Base {
public:
void show() override {
std::cout << "Implementation of show in Derived class" << std::endl;
}
};
In this example, Base is an abstract class because it contains a pure virtual function, show(). The Derived class inherits from Base and provides its own implementation of the show() function. You cannot create an instance of Base, but you can create instances of Derived.
int main() {
Derived d;
d.show(); // Calls the implementation in Derived
return 0;
}
Key Points to remember about pure virtual functions: They allow you to create an interface by defining methods that must be implemented in derived classes. An abstract class can have both pure virtual functions and other functions with implementations. Any derived class that does not implement all pure virtual functions becomes an abstract class itself.
class AnotherDerived : public Base {
// Missing implementation for show(), so cannot be instantiated.
};