Question

For some class C:

C* a = new C();

C* b(a);  //what does it do?

C* b = a;  //is there a difference?
Was it helpful?

Solution

C* b(a) and C* b = a are equivalent. As with many languages, there's more than one way to do it...

OTHER TIPS

Note that in

C* a = new C();
C* b(a);  

b is a pointer to a C object assigned the same value as a. However,

#include "somefile.h"
C* b(a);  

we could just as easily be defining b as a function which takes an object of type a, and returns a pointer to C.

The standard describes the different kinds of initialization is 8.5, and these two specifically under 8.5/12.

C* b(a);  //what does it do?

This is called direct initialization. If 'b' had class type, then the compiler would perform overload resolution on the constructors in C using 'a' as an argument. For a pointer type, it simply initializes 'b' with 'a'.

C* b = a;  //is there a difference?

The standard does consider these to be different in some cases, the above syntax is called copy initialization. As for direct initialization as 'b' is not a class type, then it is initialized with the value of 'a'. If 'a' and 'b' are the same class type, then direct initialization is used.

Where 'b' is a class type and 'a' has a different type (class or not) then the rules are slightly different (8.5/14-b1.b3). So for the following code:

C b = a;

Firstly, an attempt is made to convert 'a' to type 'C' and then this temporary object is used to initialize 'b'. This is significant as you can have a situation where direct initialization succeeds but copy initialization fails:

class A {
public:
  operator int ();
};

class B {
public:
  B (int);
};

void foo ()
{
  A a;
  B b1 (a);  // Succeeds
  B b2 = a;  // Fails
}
  1. C* a = new C(); Now it is creating a pointer of type C, which also allocate new memory by using new keyword....
  2. Following statement is depend upon your constructor logic. C* b(a); //what does it do?
  3. Your first and third statement are equivalent. C* b = a; //is there a difference?

The first one creates a new instance of C and puts its address in a.

The second one is a pointer-to-function declaration. This pointer can point to any function taking an argument of type a and returns a pointer to an object of type C.

The third one declares b, a pointer to an object of type C and initializes it with a.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top