Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default constructor for int [duplicate]

Tags:

Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

In an answer to this question it's said that

ints are default-constructed as 0, as if you initialized them with int(). Other primitive types are initialized similarly (e.g., double(), long(), bool(), etc.).

Just while I was explaining this to a colleague of mine I made up the following code, compiled (gcc-4.3.4) and ran, and observed unexpected behavior.

#include <iostream>  int main() {   int i();    std::cout << i << std::endl; // output is 1 } 

Why is the output 1 and not 0 ?

like image 464
moooeeeep Avatar asked Jun 20 '12 10:06

moooeeeep


People also ask

Is there a default copy constructor?

There is no such thing as a default copy constructor. There are default constructors and copy constructors and they are different things.

Is there a default copy constructor in Java?

Like C++, Java also supports a copy constructor. But, unlike C++, Java doesn't create a default copy constructor if you don't write your own.

What is a default constructor in C++?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

Is copy constructor and default constructor same?

Unlike the default constructor, the body of the copy constructor created by the compiler is not empty, it copies all data members of the passed object to the object which is being created.


1 Answers

Most vexing parse comes into play here. You're actually declaring a function i, not an int variable. It shouldn't even compile (unless you actually have a function i defined somewhere... do you?).

To value-initialize the int, you need:

int i = int();  
like image 127
Luchian Grigore Avatar answered Oct 02 '22 07:10

Luchian Grigore