Constructor Invocation Errors: Understanding "Request for Member in Non-class Type"
When instantiating objects with specific constructor parameters, programmers may encounter the error "request for member '..' in '..' which is of non-class type." Comprehending the source of this error is crucial for resolving it effectively.
The code example provided demonstrates the issue. The class Foo possesses two constructors: a default constructor with no arguments and a constructor that accepts a single integer parameter. Instantiating foo1 using the parameterized constructor functions as intended. However, invoking the default constructor results in a compilation error.
Why does this occur? The syntax
Foo foo2();
misconstrues itself as a function declaration. The compiler perceives it as declaring a function named foo2 with a return type of Foo, expecting arguments based on the parentheses. However, the intention is to instantiate an object named foo2 using the default constructor, which does not take any arguments.
Consequently, the compiler designates foo2 as a non-class type named Foo(). This designation prevents access to the methods defined within the Foo class, thus rendering the invocation of foo2.bar() invalid.
To rectify this error, the syntax should be adjusted to:
Foo foo2;
By omitting the parentheses, the compiler interprets
Foo foo2
as an object declaration of foo2 using the default constructor. This will successfully instantiate an object of type Foo, allowing access to its member functions, including bar().
The above is the detailed content of Why Does 'Foo foo2();' Cause a 'Request for Member in Non-class Type' Error?. For more information, please follow other related articles on the PHP Chinese website!