Encapsulation and Extensibility of Types
Overview
Object-Oriented Programming (OOP) in MQL4 emphasizes encapsulation, bundling data and behavior into user-defined data types that extend basic language types. Type extensibility allows for the creation of user-defined types that are as easy to use as basic types.
Core Concepts
MQL4 Implementation
class and struct are used for encapsulation.public: Members are accessible without restrictions.
* protected: Members are accessible within the class and its inheritor classes.
* private: Members are accessible only by member functions of their own class.
public access.Example 1: Basic Encapsulation
class CPerson {
protected:
string m_name; // name
public:
void SetName(string n) { m_name = n; } // sets name
string GetName() { return(m_name); } // returns name
};
This approach allows changing the internal implementation of SetName and GetName without affecting external code that uses CPerson objects.
Example 2: Advanced Encapsulation with Structs
struct Name {
string first_name; // name
string last_name; // last name
};class CPerson {
protected:
Name m_name; // name
public:
void SetName(string n);
string GetName() { return(m_name.first_name + " " + m_name.last_name); }
private:
string GetFirstName(string full_name);
string GetLastName(string full_name);
};
void CPerson::SetName(string n) {
m_name.first_name = GetFirstName(n);
m_name.last_name = GetLastName(n);
}
string CPerson::GetFirstName(string full_name) {
int pos = StringFind(full_name, " ");
if (pos > 0) StringSetCharacter(full_name, pos, 0);
return(full_name);
}
string CPerson::GetLastName(string full_name) {
string ret_string;
int pos = StringFind(full_name, " ");
if (pos > 0) ret_string = StringSubstr(full_name, pos + 1);
else ret_string = full_name;
return(ret_string);
}
This example demonstrates encapsulating name logic within CPerson and its helper private functions.