(Mql4) What differentiates a "Method" from a "Constructor"? - class

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?

Basic information and differences between constructor and method:
Constructor:
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,
The name of a constructor must match the class name,
The constructor has no return type (you can specify the void type).
(docs)
Method:
A method is a function that belongs to a class or an object, i.e. it cannot exist without the class.
You need to declare class methods in the class. Else it wouldn't be a class method.
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

Dart - Way to access a inherited static property from a parent class method

In PHP there is a way of accessing a static property value that is defined/overridden on an inheritor.
e.g.
class Foo {
public static $name='Foo';
public function who(){
echo static::$name;//the static operator
}
}
class Bar extends Foo {
public static $name='Bar';
}
$bar = new Bar();
$bar->who();
//Prints "Bar";
Is there ANY way of doing the exact same thing in Dart language?
Addressing comments:
About making it instance prop/method: There's a reason for the existence of static properties and methods and it's not having to create a new instance of the object to access a value or functionality that is not mutable.
Yes, but that's not how you are using it. Your use case is to invoke the method on an object, and therefore you really want an instance method. Now, some languages automatically allow invoking class methods as instance methods, and I see two choices for a language that offers that ability:
Statically transform fooInstance.classMethod() to ClassFoo.classMethod() based on the declared type (not the runtime type) of the object. This is what Java and C++ do.
Implicitly generate virtual instance methods that call the class method. This would allow fooInstance.classMethod() to invoke the appropriate method based on the runtime type of the object. For example, given:
class Foo {
static void f() => print('Foo.f');
}
You instead could write:
class Foo {
static void classMethod() => print('Foo.f');
final instanceMethod = classMethod;
}
and then you either could call Foo.classMethod() or Foo().instanceMethod() and do the same thing.
In either case, it's syntactic sugar and therefore isn't anything that you couldn't do yourself by being more verbose.
About the "meaning of static" and "only work because they allow invoking class methods as instance methods" : That affirmation is actually wrong. In the case of PHP, as per the example above, the Language is providing a way to access the TYPE of the class calling the method in the inheritance chain. A(methodA) >B > C. When C calls methodA, PHP allows you to know that the class type you're in is indeed C, but there's no object instance attached to it. the word "static" there is a replacement for the caller class type itself
All of that is still known at compilation time. That C derives from B derives from A is statically known, so when you try to invoke C.methodA, the compiler knows that it needs to look for methodA in B and then in A. There's no dynamic dispatch that occurs at runtime; that is still compile-time syntactic sugar. That is, if you wanted, you could explicitly write:
class A {
static void methodA() {}
}
class B extends A {
static void methodA() => A.methodA();
}
class C extends B {
static void methodA() => B.methodA();
}
Anyway, in your example, you could write:
class Foo {
static String name = 'Foo';
String get nameFromInstance => name;
void who() {
print(nameFromInstance);
}
}
class Bar extends Foo {
static String name = 'Bar';
#override
String get nameFromInstance => name;
}
void main() {
var bar = Bar();
bar.who(); // Prints: Bar
}

how to call member methods inside a wrapper class without repeating the method definition inside the wrapper class?

let's assume i have a wrapper class that embeds a single memeber:
class wrapper {
public:
Object obj;
// the rest ...
};
if the member variable obj has some methods, how can i call the member variable method without explicitly defining methods in the wrapper class like this?
class wrapper{
public:
void foo { obj.foo (); }
int bar (int x) {return obj.bar(x); }
};
i know this is doable in python, but how can i have the same functionality in c++?
ps- please note i don't want to inherit from the member class. this wouldn't't be a wrapper class by definition. i want to achieve this through composition instead.
There are a few ways to handle this. One would be to create a getter to return the wrapper object and another is to override the typecast operator:
class Object {
public:
void foo() {cout << "test" << endl;}
};
class wrapper {
protected:
Object obj;
public:
operator Object&() {return obj;}
Object& getObject() {return obj;}
};
void f(A& a) {
a.foo();
}
int main() {
wrapper w;
((Object)w).foo();
w.getObject().foo();
f(w);
return 0;
}
As you can see, the typecast operator requires you to cast the wrapper object, except when passing as a parameter to the function f().
Also, in your example you already have the obj member as public so it is exposed. You could just:
wrapper w;
w.obj.foo();
Here's a discussion on that: What good are public variables then?

Autofac parameterless constructor selection

"Autofac automatically chooses the constructor with the most parameters that are able to be obtained from the container." I want it to do otherwise and choose the default constructor instead. http://code.google.com/p/autofac/wiki/Autowiring
internal class ParameterlessConstructorSelector : IConstructorSelector
{
#region Implementation of IConstructorSelector
/// <summary>
/// Selects the best constructor from the available constructors.
/// </summary>
/// <param name="constructorBindings">Available constructors.</param>
/// <returns>
/// The best constructor.
/// </returns>
public ConstructorParameterBinding SelectConstructorBinding(ConstructorParameterBinding[] constructorBindings)
{
return constructorBindings.First();
}
#endregion
}
When I wire the class, I did this:
builder.RegisterType<EmployeeFactory>()
.As<IEmployeeFactory>().UsingConstructor(new ParameterlessConstructorSelector())
.SingleInstance();
The first binding in the constructorBindings list is always the one with paremeterless constructor. Not sure if it defined first or the way autofac scans the constructors but is this the right approach to wire for parameterless constructor?
Thanks
Autofac internally uses the Type.GetConstructors method to discover the constructors.
From the methods documentation:
The GetConstructors method does not return constructors in a
particular order, such as declaration order. Your code must not depend
on the order in which constructors are returned, because that order
varies.
So it was just luck that it worked with the First() in your case. In a proper implementation you need to explicitly search for the constructor with 0 arguments:
public class DefaultConstructorSelector : IConstructorSelector
{
public ConstructorParameterBinding SelectConstructorBinding(
ConstructorParameterBinding[] constructorBindings)
{
var defaultConstructor = constructorBindings
.SingleOrDefault(c => c.TargetConstructor.GetParameters().Length == 0);
if (defaultConstructor == null)
//handle the case when there is no default constructor
throw new InvalidOperationException();
return defaultConstructor;
}
}
You can test the theory with this very simple class:
public class MyClass
{
public readonly int i;
public MyClass(int i)
{
this.i = i;
}
public MyClass()
{
i = 1;
}
}
With your implementation:
var builder = new ContainerBuilder();
// register 22 for each integer constructor argument
builder.Register<int>(v => 22);
builder.RegisterType<MyClass>().AsSelf()
.UsingConstructor(new ParameterlessConstructorSelector());
var c = builder.Build();
var myClass = c.Resolve<MyClass>();
Console.WriteLine(myClass.i);
It outputs 22 e.g the constructor with the int argument is called:
With my implementation:
//...
builder.RegisterType<MyClass>().AsSelf()
.UsingConstructor(new DefaultConstructorSelector());
//...
var myClass = c.Resolve<MyClass>();
Console.WriteLine(myClass.i);
It outputs 1 e.g the default constructor is called.
Wouldn't it be simpler to just explicitly register the default constructor?
builder.Register<EmployeeFactory>(c => new EmployeeFactory())
.As<IEmployeeFactory>()
.SingleInstance();
With recent versions of Autofac, this is very simple :
builder.RegisterType<EmployeeFactory>()
.As<IEmployeeFactory>().UsingConstructor()
.SingleInstance();
Calling "UsingConstructor" with no parameters means "use parameterless constructor".
See https://autofac.org/apidoc/html/EB67DEC4.htm and related pages.

Writing methods and constructors

OK, i need someone to explain to me where to start on this project.
First I need to overload the constructor by adding a default (no-args) constructor to Person that defines an object to have the name "N/A" and an id of -1.
Then i need to add a setter method named reset that can be used to reset the two private instance variables of this class to two values passed in as parameters.
Then I need to add a getter method named getName and getId that can be used to retrieve these two private variables
Here is the code:
public class Person
{
private String name;
private int id;
private static int personCount = 0;
// constructor
public Person(String pname)
{
name = pname;
personCount++;
id = 100 + personCount;
}
public String toString()
{
return "name: " + name + " id: " + id
+ " (Person count: " + personCount + ")";
}
// static/class method
public static int getCount()
{
return personCount;
}
////////////////////////////////////////////////
public class StaticTest
{
public static void main(String args[])
{
Person tom = new Person("Tom Jones");
System.out.println("Person.getCount(): " + Person.getCount());
System.out.println(tom);
System.out.println();
Person sue = new Person("Susan Top");
System.out.println("Person.getCount(): " + Person.getCount());
System.out.println(sue);
System.out.println("sue.getCount(): " + sue.getCount());
System.out.println();
Person fred = new Person("Fred Shoe");
System.out.println("Person.getCount(): " + Person.getCount());
System.out.println(fred);
System.out.println();
System.out.println("tom.getCount(): " + tom.getCount());
System.out.println("sue.getCount(): " + sue.getCount());
System.out.println("fred.getCount(): " + fred.getCount());
}
}
I'm not exactly sure where to start and I don't want just the answer. I'm looking for someone to explain this clearly.
First I need to overload the constructor by adding a default (no-args) constructor to Person that defines an object to have the name "N/A" and an id of -1.
Read about constructors here.
The Person class already contains a ctor that takes 1 argument. What you need to do is create a "default ctor" which is typically a ctor w/out any parameters.
Example:
class x
{
// ctor w/ parameter
//
x(int a)
{
// logic here
}
// default ctor (contains no parameter)
//
x()
{
// logic here
}
}
Then i need to add a setter method named reset that can be used to reset the two private instance variables of this class to two values passed in as parameters.
Setter methods are used to "encapsulate" member variables by "setting" their value via public function. See here.
Example:
class x
{
private int _number;
// Setter, used to set the value of '_number'
//
public void setNumber(int value)
{
_number = value;
}
}
Then I need to add a getter method named getName and getId that can be used to retrieve these two private variables
Getters do the opposite. Instead of "setting" the value of a private member variable, they are used to "get" the value from the member variable.
Example:
class x
{
private int _number;
// Getter, used to return the value of _number
//
public int getNumber()
{
return _number;
}
}
Hope this helps
I highly recommend consulting the Java Tutorials, which should be very helpful here. For example, there is a section on constructors which details how they work, even giving an example of a no-argument form:
Although Bicycle only has one constructor, it could have others, including a no-argument constructor:
public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}
Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.
Similarly, there are sections dedicated to defining methods and passing information to them. There's even a section on returning values from your method.
Read the above and you should be able to complete your homework :-)

Creating an object passing a lambda expression to the constructor

I have an object with a number of properties.
I want to be able to assign some of these properties when I call the constructor.
The obvious solution is to either have a constructor that takes a parameter for each of the properties, but that's nasty when there are lots. Another solution would be to create overloads that each take a subset of property values, but I could end up with dozens of overloads.
So I thought, wouldn't it be nice if I could say..
MyObject x = new MyObject(o => o.Property1 = "ABC", o.PropertyN = xx, ...);
The problem is, I'm too dim to work out how to do it.
Do you know?
C# 3 allows you to do this with its object initializer syntax.
Here is an example:
using System;
class Program
{
static void Main()
{
Foo foo = new Foo { Bar = "bar" };
}
}
class Foo
{
public String Bar { get; set; }
}
The way this works is that the compiler creates an instance of the class with compiler-generated name (like <>g__initLocal0). Then the compiler takes each property that you initialize and sets the value of the property.
Basically the compiler translates the Main method above to something like this:
static void Main()
{
// Create an instance of "Foo".
Foo <>g__initLocal0 = new Foo();
// Set the property.
<>g__initLocal0.Bar = "bar";
// Now create my "Foo" instance and set it
// equal to the compiler's instance which
// has the property set.
Foo foo = <>g__initLocal0;
}
The object initializer syntax is the easiest to use and requires no extra code for the constructor.
However, if you need to do something more complex, like call methods, you could have a constructor that takes an Action param to perform the population of the object.
public class MyClass
{
public MyClass(Action<MyClass> populator)
{
populator.Invoke(this);
}
public int MyInt { get; set; }
public void DoSomething()
{
Console.WriteLine(this.MyInt);
}
}
Now you can use it like so.
var x = new MyClass(mc => { mc.MyInt = 1; mc.DoSomething(); });
Basically what Andrew was trying to say is if you have a class (MyObject for eg) with N properties, using the Object Initializer syntax of C# 3.0, you can set any subset of the N properties as so:
MyObject x = new MyObject {Property1 = 5, Property4 = "test", PropertyN = 6.7};
You can set any of the properties / fields that way./
class MyObject
{
public MyObject(params Action<MyObject>[]inputs)
{
foreach(Action<MyObject> input in inputs)
{
input(this);
}
}
}
I may have the function generic style wrong, but I think this is sort of what you're describing.