sanjeev
sanjeev

Reputation: 600

Why result is outputted to 1

I am having a simple program as shown below

#include<iostream>

using namespace std;

class A
{

  public:
    A()
    {
      int a();
      cout<<"\n value of A is:-  "<<a<<"\n\n";
    }
};

int main()
{
  A obj;
  return 0;
}

The above program is outputting one, although I am not passing any value to variable a. Is it some task constructor is performing or some other type of default constructors are called, if I keep () with any variable.

Same is happening for float datatype also.

It look simple but I want to understand the concept behind this. Can someone please help me with that?

Upvotes: 1

Views: 80

Answers (3)

Jesper Juhl
Jesper Juhl

Reputation: 31447

You seem to be under the impression that int a(); declares a variable. That is not correct. You are declaring a function named a with no parameters that returns int.

What you probably intended is int a;.

Also, you must initialize a variable before reading it (like in your output statement) or else the program will contain undefined behaviour and has no meaning and the compiler is free to generate whatever code it likes. Not a situation you want to be in, so what you really want is int a = 0;.

As to why you get 1 as output; the a is being converted to bool (true) which prints as 1.

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172864

According to Most vexing parse, int a(); is function declaration, which takes no parameters and returns int. When you output it will decay to function pointer which is not null, and then converted to bool true, so the result is 1 here.

If you just want to declare it you could

int a;

If you want to declare and initialize it you could

int a = 1; // initialized with the specified value
int a{2};  // initialized with the specified value, since C++11
int a{};   // initialized with 0, since C++11

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119044

int a() declares a function named a, taking no arguments and returning int. When you try to output a function, it gets converted to a function pointer, which in turn is converted to bool. The address of a function will always be non-null, so it gets converted to true, which is printed as 1.

Note however that you are violating the One Definition Rule: you're not allowed to take the address of a function if the function lacks a definition. However, the compiler is not required to diagnose violations of the ODR. In this particular case, the compiler decides it doesn't care about the actual address, since it knows that it will be non-null no matter what.

If you want to declare an int and value-initialize it, the correct syntax is

int a{};

http://coliru.stacked-crooked.com/a/6d10bdd34c238ab6

Upvotes: 4

Related Questions