4

First:

int *p = new int;

Second:

class A{};

A *pa = new A;

How does new and compiler determines when to call constructor? In first case compiler does not generate code to call constructor of p and in second case it generates code to call constructor of A. Which mechanism is used to make such choice?

Vikas
  • 179
  • 1
  • 8
  • 3
    Your second code snippet *does not* call any constructor of A (5.3.4/15, we're in the case where "the object created has indeterminate value"), although since the compiler-generated default constructor does nothing, that's a bit of a moot point in this example. See http://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new – Steve Jessop Dec 17 '10 at 12:36

2 Answers2

7

The compiler knows that A is a class, because it has seen the class declaration, so it uses the synthesised default constructor. It knows an int is an int, because the language grammar says it is.

unquiet mind
  • 1,082
  • 6
  • 11
6

In your case A is a POD as well. To learn the correct definition of POD's take a look at this.

As far as your code is concerned, the compiler knows that int is a built-in type and doesn't have a constructor whatsoever.

Edit: Your question is rather strange. The compiler knows which type is a pod, and which isn't, also it knows which are built-in and not-built in because it is the compiler that compiles your code :) If the compiler didn't know that information, who would?

Community
  • 1
  • 1
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434