Pregunta

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?

¿Fue útil?

Solución 2

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.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top