3 June 2016
3 June 2016
class CAnimal { public: CAnimal(); // Constructor virtual void Sound() = 0; // A pure virtual function private: double m_legs_count; // How many feet the animal has };Here Sound() is a pure virtual function, because it is declared with the specifier of the pure virtual function PURE (=0).
class CAnimal { public: virtual void Sound()=NULL; // PURE method, should be overridden in the derived class, CAnimal is now abstract and cannot be created }; //--- Derived from an abstract class class CCat : public CAnimal { public: virtual void Sound() { Print("Myau"); } // PURE is overridden, CCat is not abstract and can be created }; //--- examples of wrong use new CAnimal; // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract class" error CAnimal some_animal; // Error of 'CAnimal' - the compiler returns the "cannot instantiate abstract class" error //--- examples of correct use new CCat; // no error - the CCat class is not abstract CCat cat; // no error - the CCat class is not abstractRestrictions on abstract classes
//+------------------------------------------------------------------+ //| An abstract base class | //+------------------------------------------------------------------+ class CAnimal { public: //--- a pure virtual function virtual void Sound(void)=NULL; //--- function void CallSound(void) { Sound(); } //--- constructor CAnimal() { //--- an explicit call of the virtual method Sound(); //--- an implicit call (using a third function) CallSound(); //--- a constructor and/or destructor always calls its own functions, //--- even if they are virtual and overridden by a called function in a derived class //--- if the called function is purely virtual //--- the call causes the "pure virtual function call" critical execution error } };However, constructors and destructors for abstract classes can call other member functions.
typedef int (*TFunc)(int,int);Now, TFunc is a type, and it is possible to declare the variable pointer to the function:
TFunc func_ptr;The func_ptr variable may store the pointer to function to declare it later:
int sub(int x,int y) { return(x-y); } int add(int x,int y) { return(x+y); } int neg(int x) { return(~x); } func_ptr=sub; Print(func_ptr(10,5)); func_ptr=add; Print(func_ptr(10,5)); func_ptr=neg; // error: neg is not of int (int,int) type Print(func_ptr(10)); // error: there should be two parametersPointers to functions can be stored and passed as parameters. You cannot get a pointer to a non-static class method.
Fixed errors reported in crash logs.