How do I initialize a const data member?

The const variable specifies whether a variable is modifiable or not. The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution. Bjarne Stroustrup’s explanation sums it up briefly: A class is typically declared in a header file and a header file is typically … Read more

C++ Member Initializer List

Just to clarify something that came up in some of the other answers… There is no requirement that the initializer list be in either the source (.cpp) or header (.h) file. In fact, the compiler does not distinguish between the two types of files. The important distinction is between the contructor’s declaration and it’s definition. … Read more

Default vs. Implicit constructor in C++

The terms default and implicit, when talking about a constructor have the following meaning: default constructor is a constructor that can be called with no arguments. It either takes no arguments or has default values for each of the arguments taken. implicit constructor is a term commonly used to talk about two different concepts in … Read more

Why can’t I refer to an instance method while explicitly invoking a constructor?

Non-static methods are instance methods. This are only accessible in existing instance, and instance does not exist yet when you are in constructor (it is still under construction). Why it is so? Because instance methods can access instance (non-static) fields, which can have different values in different instances, so it doesn’t make sense to call … Read more

OO Javascript constructor pattern: neo-classical vs prototypal

This looks like the non-singleton version of the module pattern, whereby private variables can be simulated by taking advantage of JavaScript’s “closures”. I like it (kinda…). But I don’t really see the advantage in private variables done in this way, especially when it means that any new methods added (after initialisation) do not have access … Read more

Asynchronous constructor

Update 2: Here is an updated example using an asynchronous factory method. N.B. this requires Node 8 or Babel if run in a browser. class Element { constructor(nucleus){ this.nucleus = nucleus; } static async createElement(){ const nucleus = await this.loadNucleus(); return new Element(nucleus); } static async loadNucleus(){ // do something async here and return it … Read more

In Scala, how can I subclass a Java class with multiple constructors?

It’s easy to forget that a trait may extend a class. If you use a trait, you can postpone the decision of which constructor to call, like this: trait Extended extends Base { … } object Extended { def apply(arg1: Int) = new Base(arg1) with Extended def apply(arg2: String) = new Base(arg2) with Extended def … Read more