Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor vs. new

I just wanted to confirm the difference here, take this as an example:

class Gate
{
   public:
           Gate(); //Constructor
           void some_fun();
   private:
           int one, two;
           ptr p1;
           Gate* next;
};
typedef Gate* ptr;

Gate::Gate()
{
  one = 0;
  two = 0;
}

void Gate::some_fun()
{
  p1 = new Gate;
  p1 = p1->next;
  p1 = new Gate();
}

In my example, I have created 2 new nodes of "Gate" and the only difference between them is that the first node does not have the variables "one and two" initialized, while the second one does.

like image 374
Josh Avatar asked Dec 28 '22 03:12

Josh


1 Answers

C++ has two classes of types: PODs and non-PODs (“POD” stands for “plain old data” … a somewhat misleading hint).

For non-PODs, there is no difference between new T and new T(). The difference only affects PODs, for which new T doesn’t initialise the memory, whereas new T() will default-initialise it.

So what are PODs? All built-in C++ types (int, bool …) are.

Furthermore, certain user-defined types are as well. Their exact definition is somewhat complicated but for most purposes it’s enough to say that a POD cannot have a custom constructor (as well as certain other functions) and all its data members must themselves be PODs. For more details, refer to the linked FAQ entry.

Since your class isn’t a POD, both operations are identical.

like image 157
Konrad Rudolph Avatar answered Jan 09 '23 03:01

Konrad Rudolph