Constructors for primitive data types

Is an

int i(10);

      

the same as

int i = 10 ;

      

What are the differences in both methods?

+3


source to share


4 answers


Quoting the standard (§8.5 / 14):

The form of initialization (using parentheses or =) is usually minor, but does matter when an initializer or object is initialized to a class type; see below.



So, in your case, there is no difference ("see below" refers to the differentiation between initialization and direct initialization, but since we're talking about int

, this is not of interest here).

+2




One of the differences between the two:

/*1*/ int a(10);
/*2*/ int a = 10;

      

is that the first one cannot be used as an element initializer in a class:

struct A
{
    int a(10); // compilation error
};

      

whereas the second could be:

struct A
{
    int a = 10;
};

      



As with any other place where copy or equal-initializer (defined below) is required.

brace-or-equal-initializer:
    = initializer-clause
    braced-init-list

braced-init-list:
    { initializer-list ,opt }
    { }

      

Link:

§ 9.2 Class Members [class.mem]

  1. An initializer based on parentheses or equal to must appear only in an item declaration. (For static data members, see 9.4.2, for non-static data members, see 12.6.2).

which means the following could be used instead:

struct A
{
    int a{10};
};

      

+1


source


Same.

int i = 10 // initializes memory  and loads with value 10.

int i(10) // does the same just writing style is different.It is like initializing a class of int.

      

0


source


int i (10) ;: - this slowdown is the wrong way to declare a method. declare a method that needs a return type for the method, the method name, and the argument list that is used inside the method. int i (10) is the wrong method slowdown.

int i = 10: - means i is a variable of type int which has 10 values. both are different in meanings

to initialize a variable from a constructor, we use this:

class I {
int i;
i(int i) {
this.i=i;
}
psvm(string []m){
I i= new I(10);
}
 }

      

-2


source







All Articles