0

I have the following class:

class aClass {
public:
    aClass():a(0){}
    void print(){cout<<a<<endl;}
private:
    int a;
};

In main() function I accidentally create an object like this:

aClass obj();

I thought the compiler will throw an error as it is expected to call the default copy constructor, but there is no argument inside the bracket (). Interestingly, there is no error at all. So I try to access a member function by calling:

obj.print();

Now it throws this error:

request for member 'print' in 'obj', which is of non-class type 'aClass()'

Can somebody explain it to me? What is obj() that has been created?

Tu Bui
  • 1,660
  • 5
  • 26
  • 39

2 Answers2

4
aClass obj();

This is not an instance of class aClass created by it's default constructor.

It is a function prototype of a function taking no parameters and returning an aClass.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Can you explain more by showing what it would look like if it was an instance of that class being created by the default constructor? – starsplusplus Jan 21 '14 at 12:10
  • @starsplusplus "aClass obj;" without the brackets would be a default-constructed instance of an aClass. – nvoigt Jan 21 '14 at 12:31
1

That's a function declaration.

The language allows function declarations inside other functions; the effect is to declare a function in the surrounding namespace, but only to make the name available within the declaration's scope.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644