Home > Backend Development > C++ > Why Does 'Foo foo2();' Cause a 'Request for Member in Non-class Type' Error?

Why Does 'Foo foo2();' Cause a 'Request for Member in Non-class Type' Error?

Barbara Streisand
Release: 2024-12-01 01:22:11
Original
472 people have browsed it

Why Does

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();
Copy after login

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;
Copy after login

By omitting the parentheses, the compiler interprets

Foo foo2
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template