C++ tricks Class constructor / object initialization discussions with chatGpt

  class XXX{

      int a;

      long b;

      std::string c;

    public:

      XXX(const int&a,const long&b,const std::string&c):a(a),b(b),c(c){}

    };

     class YYY{

      int a;

    public:

      YYY(const int&a):a(a){}

    };

    void fn(){

      std::vector<XXX> vec{{4, 5, "aa"}};

      std::vector<XXX> vec0{4, 5, "aa",10,8,"cc"};

      std::vector<YYY>vec2{4,5,6,8,10};

    }
vec,vec2 working, but vec0 not working

--------------------------------------------

The issue with vec0 is related to how you're trying to initialize the vector of XXX objects. When you attempt:

cpp
std::vector<XXX> vec0{4, 5, "aa", 10, 8, "cc"};

you're providing multiple arguments, but this syntax doesn't match the expected initialization format for a std::vector of objects. The correct way to initialize a vector with multiple XXX objects using initializer list is to group the arguments into separate object constructions, like this:

Correct Initialization:

cpp
std::vector<XXX> vec0{{4, 5, "aa"}, {10, 8, "cc"}};

Explanation:

  • The outer curly braces {} represent the entire initializer list for the vector.
  • The inner curly braces {{4, 5, "aa"}, {10, 8, "cc"}} represent the individual objects being initialized with their respective constructor arguments.

For vec2:

Your initialization works fine because you're simply providing the integers, which correspond to the constructor of YYY.

cpp
std::vector<YYY> vec2{4, 5, 6, 8, 10};

Here, each integer is passed as a single argument to the YYY constructor.

Final Working Example:

cpp
void fn() { std::vector<XXX> vec{{4, 5, "aa"}}; // Correct std::vector<XXX> vec0{{4, 5, "aa"}, {10, 8, "cc"}}; // Correct std::vector<YYY> vec2{4, 5, 6, 8, 10}; // Correct }

This should work without issues.

No comments:

Post a Comment

If you have any doubts, please let me know.

Various types of salts effect on health (discussion with gemenie)

Is  rock salt or bitnoon helps in digestion or just a airuvedic nuska This is for informational purposes only. For medical advice or diagnos...