Home > Net >  (Mql4) What differentiates a "Method" from a "Constructor"?
(Mql4) What differentiates a "Method" from a "Constructor"?

Time:11-10

My question refers to Methods inside of Classes via "public" access.

As referring to mql4 documentation, there seems to be no listed source on how to properly instantiate a Method into a Class, or what even makes a Method a Method in the first place.

To me it seems that if you place a function inside of a Class, that in itself makes it a Method? Or am I wrong. Is anyone able to clear this up for me?

CodePudding user response:

Basic information and differences between constructor and method:

Constructor:

  1. A constructor is a special function, which is called automatically when creating an object of a structure or class and is usually used to initialize class members,
  2. The name of a constructor must match the class name,
  3. The constructor has no return type (you can specify the void type).

(docs)

Method:

  1. A method is a function that belongs to a class or an object, i.e. it cannot exist without the class.
  2. You need to declare class methods in the class. Else it wouldn't be a class method.
  3. Method can return value with type specified in the method declaration.

Simple example:

class MyClass {                            // Declaration
    private:
        string myName;                     // Property
    public:
        void printName();                  // Method of void return type
        int sumIntegers(int a, int b);     // Method of int return type
        MyClass(string name);              // Constructor declaration
};

MyClass::MyClass(string name) {            // Constructor body
    this.myName = name;
}

int MyClass::sumIntegers(int a, int b) {   //Method body
    return a   b;
}

void MyClass::printName() {
    Print("Your name is: ", this.myName);
}

int sumIntegers(int a, int b){             //Function body
    return a   b;
}

Class member (object) initialization:

MyClass *myObject = new MyClass("SO example");

Example usage inside OnInit:

int OnInit() {
    myObject.printName();                            // Method call by object (MyClass)
    Alert("2   2 = ", myObject.sumIntegers(2, 2));   // Same as above 
    Alert("2   2 = ", sumIntegers(2, 2));            // Function call

    return(INIT_SUCCEEDED);
}

To me it seems that if you place a function inside of a Class, that in itself makes it a Method?

Yes, but remember that a function is a block of code which only runs when it is called, and it's not related with a class.

Methods are related with class, and can not exists without a class.

  • Related