0
class Int {
    int n;

public:

    Int(int n) {
        this->n = n;
    }

};

vs

class Int {
    int n;

public:

    Int(int n) : n(n){
    }

};

What is essentially the difference between these two and when should one use the this keyword when creating a new object of a given class?

Zong
  • 6,160
  • 5
  • 32
  • 46
Boyan Kushlev
  • 1,043
  • 1
  • 18
  • 35

1 Answers1

4

The biggest difference is the second one is the recommended way as it avoids double-initializing properties. An int is a trivial case, but you can imagine you might have some expensive structure in there that would get initialized twice:

Complicated(const HeavyObject& _h) : h(_h) {
  // h only initialized once
}

Complicated(const HeavyObject& _h) {
  // h already initialized with default constructor

  // Copy to object, potentially initializing all over again.
  this->h = _h;
}
tadman
  • 208,517
  • 23
  • 234
  • 262
  • It's a bit of a nitpick, but `this->h = _h` is an assignment, not an initialization, although your point about not constructing twice is correct. – TriskalJM Apr 19 '16 at 17:30
  • I prefer the postfix version `h_` since prefix `_` seems to be reserved for internals (questionable if this rule could ever apply to parameters, but well for sake of consistency). – πάντα ῥεῖ Apr 19 '16 at 17:30
  • @πάνταῥεῖ Yeah, I've seen some wildly different standards for internal vs external naming conventions. This is just an example. – tadman Apr 19 '16 at 17:31
  • @πάνταῥεῖ As long as it's just a single underscore followed by a lowercase letter in a non-global scope, it's fine. But I don't like it either. – Baum mit Augen Apr 19 '16 at 17:31
  • In `template` s, the `this` pointer is required in certain scenarios irrespective of constructors or member methods. BTW, the example you have given doesn't require `this` necessarily as the variable names are different. – iammilind Apr 19 '16 at 17:33
  • 2
    @Baum I mostly use the postfix `_` for class member variables anyway (thus it's the other way round regarding the parameters), because it lets me smoothly provide getter and setter functions named `int h() const;` and `void h(int);`. – πάντα ῥεῖ Apr 19 '16 at 17:38