Parenthesis Confusion while creating objects

Parenthesis Confusion while creating objects - C++


Let's see some notations of trying to create objects in different ways of creating objects

  1. ClassName obj1;
  2. ClassName obj2();
  3. ClassName *obj3 = new ClassName;
  4. ClassName *obj4 = new ClassName();

So, which and all the above statements create objects:


  1. ClassName obj1 - Yes.
    • Object obj1 is created on stack.
  2. ClassName obj2(); - No.
    • C++ compiler will interpret "obj2" as a function definition with no parameters and which returns a ClassName object.
  3. ClassName *obj3 = new ClassName; - YES
    • obj3 will be created as a default initialized, which means all POD data types will be left unitialized.
  4. ClassName *obj4 = new ClassName(); - YES
    • obj4 will be created as a value initialized, which means all data members will be initialized. Init will be zero-initialized.
So, what is a POD class ? POD means "Plain Old Data". In C++, objects are either POD or non-POD. A POD class is said to have data members of one the following data-types : built-in data types (int,double....), pointer, struct, array or a class witch compiler generated constructor. POD class cannot have other data types that are non-POD (string data type is not a POD class because it has a defined constructor). 

Below are the things that would make a class non-POD even if it contains any of the members mentioned above.
  1. User defined Constructor
  2. User defined Copy Constructor
  3. User defined assignment operator
  4. User defined destructor
  5. Non-POD data types such as a string or a non-POD class.

In Summary, POD class objects are default initialized, which means that all POD data types will be left uninitialized. So, if you're not intentionally planning to leave member objects uninitialized, then 
I would recommend that you always use parenthesis at the end of your class initialization.

Comments

Popular posts from this blog

C++ Guidelines for Multithreaded System

Signalling System #7(SS7) Protocol.

std::shared_ptr