Search code examples
c++gnu

define array of class object at time of declaration with val.Class with array in constructor initializer list & ptr members assigned with member array


This is my class

#include <iostream>
#include <string>
class abc{
private:
    //int *px=x;
    //int *py=y;
    //int *pz=z;
public:
    int x[10];
    int y[10];
    int z[10];
    int *px=x;
    int *py=y;
    int *pz=z;
    abc(const int _px[],int _py[],int _pz[]):x{{10}},y{{10}},z{{10}}
    {

    }

};

I want to keep x,y,z private,

What I like to do is in main I want to declare and define array of abc and assigned the array elements so define it in the start. I tried something like this

 abc obj[5]={{{1,1,1},{2,2,2},{3,3,3}},{{...},...},.....}

so obj[0]->x[]={1,1,1}, obj[0]->y={2,2,2} obj[0]->z={3,3,3} for abc obj[0] but its not compiling. Its only allowing abc obj[5]={/*not inner curly brackets values*/}

so question is how to assign values to obj at declaration (also defining it) if above not possible then how to assign to x, y, z through px,py,pz pointers (do I need memcpy for this? but don't know how to do it)

I can also keep the x,y,z public


Solution

  • With std::array, you might do

    class abc{
    public:
        std::array<int, 10> x;
        std::array<int, 10> y;
        std::array<int, 10> z;
    
        abc(const std::array<int, 10>& x,
            const std::array<int, 10>& y,
            const std::array<int, 10>& z) : x{x},y{y},z{z}
        {}
    
    private: // Not sure why you want those members :-/ Care with copy-constructor
        int* px = x.data();
        int* py = y.data();
        int* pz = z.data();
    };
    

    With usage similar to

    abc obj[2] = {
        {{1,1,1},{2,2,2},{3,3,3}},
        {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
         {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
         {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        }
    };
    

    Demo