Home > Backend Development > C++ > Why Does My No-Argument Constructor Cause a 'Request for Member' Error?

Why Does My No-Argument Constructor Cause a 'Request for Member' Error?

Linda Hamilton
Release: 2024-12-08 21:26:11
Original
523 people have browsed it

Why Does My No-Argument Constructor Cause a

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

generates the following error:

error: request for member 'bar' in 'foo2', which is of non-class type 'Foo ()()'
Copy after login

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!

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