"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can Class Data Members Be Initialized Directly in C++?

Can Class Data Members Be Initialized Directly in C++?

Published on 2024-11-18
Browse:679

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 

class test {
public:
    void fun() {
        int a(3);
        std::cout 

The compilation fails with errors:

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

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;
};

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3