0

I am using Code::Blocks 10.05 with GCC on Windows 7. I was experimenting with C++ constructors and I compiled and executed the following program.

#include<iostream>

using namespace std;

class base {
    public:
    base() {
        cout<<"\n Constructor Invoked\n";
    }
};

int main() {
  base ob;
  return 0;
}

The output was as expected and shown below.

Constructor Invoked

But while typing the program I accidentally compiled the following program. To my surprise it compiled without any error or warning.

#include<iostream>

using namespace std;

class base {
    public:
    base() {
        cout<<"\n Constructor Invoked\n";
    }
};

int main() {
  base ob();
  return 0;
}

But the program didn't give any output, just a blank screen. But no error or warning. Since it hasn't called the constructor I assume no object was created. But why no error or warning? Am I missing something very obvious?

When I added the line cout<<sizeof(ob); I got the following error message.

error: ISO C++ forbids applying 'sizeof' to an expression of function type

So what is ob? Is it considered as a function or an object?

Please somebody explain the line of code base ob(); and what actually happens in the memory when that line of code is executed?

Thank you.

Deepu
  • 7,592
  • 4
  • 25
  • 47
  • 1
    It is a function declaration. There are many duplicates, although they might be hard to find. – juanchopanza Jul 05 '13 at 09:32
  • 3
    Read about [the most vexing parse](http://en.wikipedia.org/wiki/Most_vexing_parse). It's one of the reasons that [uniform initialization](http://en.wikipedia.org/wiki/C%2B%2B11#Uniform_initialization) was put in the C++11 standard. – Some programmer dude Jul 05 '13 at 09:33

1 Answers1

3

You have declared a function with

base ob();

It will do nothing. See here

Community
  • 1
  • 1
doctorlove
  • 18,872
  • 2
  • 46
  • 62