Home > Backend Development > C++ > C Constructor Syntax: Why Does `Foo foo2();` Cause an Error?

C Constructor Syntax: Why Does `Foo foo2();` Cause an Error?

Linda Hamilton
Release: 2024-11-30 14:13:16
Original
392 people have browsed it

C   Constructor Syntax: Why Does `Foo foo2();` Cause an Error?

Error: Requesting Member in Non-Class Type 'Non-Class Type'

When declaring objects in C , it's crucial to use the correct syntax for both constructors. In the provided code, an attempt to create an object using the no-argument constructor results in an error:

Foo foo2();
Copy after login

This syntax is incorrect as it resembles a function declaration, causing the compiler to interpret it as such. The correct syntax for object declaration using the no-argument constructor is:

Foo foo2;
Copy after login

By removing the parentheses, the compiler will correctly recognize foo2 as an object of class Foo.

Alternatively, if you wish to use parentheses for clarity, ensure that the constructor arguments are included:

Foo foo2(1); // Explicitly pass the default argument of 1 to the no-argument constructor
Copy after login

The above is the detailed content of C Constructor Syntax: Why Does `Foo foo2();` Cause an Error?. For more information, please follow other related articles on the PHP Chinese website!

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