-2

In the code below, how can I both allocate and initialize pt at the same time. What I know is thatnew allocates but also initializes.

Grid.h

class Grid
{
    int nPt;
    double* pt;
};

Grid.cpp

Grid::Grid (const Grid& g)
{
    pt = new double [nPt];
    for (int i=0; i<nPt; ++i)
    {
        pt[i] = g.pt[i];
    }
}
Shibli
  • 5,879
  • 13
  • 62
  • 126

2 Answers2

0

The comment by Mat may suggest this:

Grid.h

class Grid
{
public:
    Grid (const Grid& g);
    std::vector<double> pt;
    // ... some more members of your grid?
};

Grid.cpp

Grid::Grid (const Grid& g): pt(g.pt) 
{
    // ... manage other members if any
}

But if we consider the Rule of three (as mentioned by πάντα ῥεῖ) is more likely to be this:

Grid.h

class Grid
{
public:
    std::vector<double> pt;
    // ... some more members of your grid?
};

Grid.cpp

// (nothing to do)

...and if there is nothing else you want to do with your Grid class so far, then better use a plain vector.

BTW: if you are searching for nPt, pt.size() is your new friend :-)

Community
  • 1
  • 1
Wolf
  • 9,679
  • 7
  • 62
  • 108
0

Yes you can do that in arrays, but only if its must. Otherwise go for vectors as suggested by others. Here is my answer in code:

#include <iostream>
using namespace std;

int main() {

//unitialise == garbage
cout << "*** Unitialised ***\n";
int* p1 = new int[3];
for(int i = 0; i < 3; i++)
    cout << i << "\t" << p1[i] << endl;

// initialise individual elements
cout << "*** Initialise individual elements ***\n";
int* p2 = new int[3] { 1, 2, 3 };
for(int i = 0; i < 3; i++)
    cout << i << "\t" << p2[i] << endl;

// initialise all elements
cout << "*** Initialise all elements ***\n";
int* p3 = new int[3] {0};
for(int i = 0; i < 3; i++)
    cout << i << "\t" << p3[i] << endl;

//initialise all elements stack array
cout << "*** Initialise stack array ***\n";
int p4[3] = {0};
for(int i = 0; i < 3; i++)
    cout << i << "\t" << p4[i] << endl;

delete[] p1;
delete[] p2;
delete[] p3;
return 0;
}

Here is the output:

*** Unitialised ***
0       6449456
1       0
2       3277144
*** Initialise individual elements ***
0       1
1       2
2       3
*** Initialise all elements ***
0       0
1       0
2       3277144
*** Initialise stack array ***
0       0
1       0
2       0

It is not possible to initialise all the elemets if you have allocated the array on heap, but you can do so if you have allocated it on stack. My suggestion is that if you are sticking with arrays then use your existing code as it is cache friendly and will hardly take any time to execute. You can find some interesting answers here and here.

Community
  • 1
  • 1
Cool_Coder
  • 4,888
  • 16
  • 57
  • 99