Overloaded Constructors and Class Member Access Error
Consider a class with two constructors, one with no arguments and another with a single integer argument. While creating objects using the latter constructor functions as intended, employing the no-argument constructor results in an error.
For instance, compiling the following code snippet:
class Foo { public: Foo() {}; Foo(int a) {}; void bar() {}; }; int main() { // This works... Foo foo1(1); foo1.bar(); // This fails... Foo foo2(); foo2.bar(); return 0; }
generates the following error:
error: request for member 'bar' in 'foo2', which is of non-class type 'Foo ()()'
This error occurs because the compiler interprets the code Foo foo2(); as a function declaration with the name 'foo2' and the return type 'Foo'. However, you intend to instantiate an object of type 'Foo' with the no-argument constructor.
To resolve this issue, modify Foo foo2(); to Foo foo2;. This change informs the compiler that you want to create an object using the default constructor.
Alternatively, you may encounter an error indicating ambiguity in overloaded constructors due to the presence of both the no-argument and single-argument constructors. In such cases, explicitly invoking the no-argument constructor using Foo foo2{}; will resolve the ambiguity.
The above is the detailed content of Why Does My No-Argument Constructor Cause a 'Request for Member' Error?. For more information, please follow other related articles on the PHP Chinese website!