-5

Consider the following example,

Aclass.h

class Aclass()
{
private: 
   int something;
   double nothing;
};

Aclass.cpp

#include "Aclass.h"

Aclass::Aclass (int x) {
    something = x;
    nothing = y;
}
//Write some functions to manipulate x and y.

So now, what is the difference if I skip initializing y in the constructor? What is the downside and how does it affect the remainder of the code? Is this a good way to code? What I know is that a constructor will create an object anyway whether x and y are initialized or even if both are not (default constructor) and constructors are used to create versatile objects.

enedil
  • 1,605
  • 4
  • 18
  • 34
hannibal
  • 21
  • 2
  • 4

2 Answers2

4

If there is no reason to initialize a variable, you don´t need this variable
=> Delete it entirely. Seriously, an uninitialized var is good for...? Nothing. (only for initializing it).

If you plan to initialize it later before it is used:
Can you guarantee that it will get a value before it is first read from, independent of how often and in what order the class methods are called? Then it´s not "wrong", but instead of tediously checking that (and risking bugs because it´s complicated), it´s far more easy to give it a value in the constructor.

No, making it more complicated on purpose is not a good way to code.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
0

Leaving any variable uninitialized will allow it to acquire some garbage value.

Result = Undefined Behaviour. And it has no pros.

Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
  • If you don't explicitly initialize an object, the default constructor is called, giving you a well-formed object. For example, `class C { std::string s;}` will print `0` when you type `C c; std::cout << c.s.length() << std::endl;`. – user904963 Nov 30 '21 at 14:58