Abstract Classes and Pure Virtual Functions
Overview
**Purpose:** Abstract classes in MQL4 are designed as base classes for creating more specific derived classes. They provide a generic entity that cannot be instantiated directly.
**Abstract Class Definition:** A class is considered abstract if it contains at least one pure virtual function.
**Pure Virtual Function Declaration:** Declared using the pure-specifier syntax = 0 or = NULL.
**Inheritance Requirement:** Derived classes must implement all pure virtual functions from the abstract base class to become instantiable. If a derived class fails to implement a pure virtual function, it also remains abstract.Syntax and Examples
**Pure Virtual Function Declaration:** virtual void Function_Name() = 0; or virtual void Function_Name() = NULL;
**Abstract Class Example (CAnimal):**
class CAnimal {
public:
virtual void Sound() = 0; // Pure virtual function
private:
double m_legs_count;
};
**Derived Class Example (CCat):**
class CCat : public CAnimal {
public:
virtual void Sound() { Print("Myau"); } // Implements pure virtual function
};
Instantiation Rules
**Forbidden:** Attempting to create an object of an abstract class type (e.g., new CAnimal; or CAnimal some_animal;) results in a compiler error: "cannot instantiate abstract class".
**Allowed:** Objects of derived classes that implement all pure virtual functions can be created (e.g., new CCat; or CCat cat;).Restrictions and Behavior
**Constructor/Destructor Calls:** Calling a pure virtual function (directly or indirectly) from within the constructor or destructor of an abstract class leads to undefined behavior or a critical runtime error ("pure virtual function call").
**Allowed Constructor/Destructor Behavior:** Constructors and destructors of abstract classes can safely call other member functions, including virtual functions that are not pure.Related Concepts
Encapsulation and Extensibility of Types
Inheritance
Polymorphism
Overload
Virtual Functions
Static Members of a Class
Function Templates
Class Templates