What’s wrong with overridable method calls in constructors?

On invoking overridable method from constructors Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the @Override is invoked, the state of the object may be inconsistent and/or incomplete. A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it: There are … Read more

How to overload __init__ method based on argument type?

A much neater way to get ‘alternate constructors’ is to use classmethods. For instance: >>> class MyData: … def __init__(self, data): … “Initialize MyData from a sequence” … self.data = data … … @classmethod … def fromfilename(cls, filename): … “Initialize MyData from a file” … data = open(filename).readlines() … return cls(data) … … @classmethod … … Read more

What is this weird colon-member (” : “) syntax in the constructor?

Foo(int num): bar(num) This construct is called a Member Initializer List in C++. Simply said, it initializes your member bar to a value num. What is the difference between Initializing and Assignment inside a constructor? Member Initialization: Foo(int num): bar(num) {}; Member Assignment: Foo(int num) { bar = num; } There is a significant difference … Read more

Can constructors be async?

Since it is not possible to make an async constructor, I use a static async method that returns a class instance created by a private constructor. This is not elegant but it works ok. public class ViewModel { public ObservableCollection<TData> Data { get; set; } //static async method that behave like a constructor async public … Read more

Struct Constructor in C++?

In C++ the only difference between a class and a struct is that members and base classes are private by default in classes, whereas they are public by default in structs. So structs can have constructors, and the syntax is the same as for classes.

Use of .apply() with ‘new’ operator. Is this possible?

With ECMAScript5’s Function.prototype.bind things get pretty clean: function newCall(Cls) { return new (Function.prototype.bind.apply(Cls, arguments)); // or even // return new (Cls.bind.apply(Cls, arguments)); // if you know that Cls.bind has not been overwritten } It can be used as follows: var s = newCall(Something, a, b, c); or even directly: var s = new (Function.prototype.bind.call(Something, null, … Read more

How to invoke the super constructor in Python?

In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified: Python-3.x class A(object): def __init__(self): print(“world”) class B(A): def __init__(self): print(“hello”) super().__init__() Python-2.x In python 2.x, you have to call the slightly more verbose version super(<containing classname>, self), which … Read more