Home > Backend Development > C++ > body text

Can Class Data Members Be Initialized Directly in C ?

Barbara Streisand
Release: 2024-11-15 02:14:02
Original
344 people have browsed it

Can Class Data Members Be Initialized Directly in C  ?

Can Class Data Members Be Directly Initialized?

In C , class data members cannot be initialized using the direct initialization syntax, (), as seen in the following example:

#include <iostream>

class test {
public:
    void fun() {
        int a(3);
        std::cout << a << '\n';
    }
private:
    int s(3);    // Compiler error
};

int main() {
    test t;
    t.fun();
    return 0;
}
Copy after login

The compilation fails with errors:

11    9 [Error] expected identifier before numeric constant
11    9 [Error] expected ',' or '...' before numeric constant
Copy after login

Why is this the case?

The C standard explicitly prohibits this syntax for class data member initialization. Early proposals for the feature's introduction cited parsing problems as the reason.

Consider this ambiguous example:

struct S {
    int i(x); // data member with initializer or...
    // ...
    static int x;
    int i(y); // member function declaration
    // ...
    typedef int y;
};
Copy after login

The standard proposes a solution:

To eliminate ambiguity, the C standard allows only the following syntax for class data member initialization:

  • = initializer-clause
  • { initializer-list }

This resolution ensures clarity and avoids the potential for misunderstanding in cases where a declaration could resemble both an object and a function declaration.

The above is the detailed content of Can Class Data Members Be Initialized Directly in C ?. 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