Dereferencing a pointer to an object inside its class - c++

I have SquareMatrix defined as such
SquareMatrix.h
#ifndef SQUAREMATRIX_H
#define SQUAREMATRIX_H
#include "Matrix.h"
#include <vector>
class SquareMatrix : public Matrix
{
public:
SquareMatrix();
SquareMatrix(std::vector<std::vector<long double> >);
//~SquareMatrix(); //just in case there is dynamic memory explicitly used
//convenient member functions exclusive to SquareMatrix
bool isUpperDiagonalMatrix() const;
static SquareMatrix identityMatrix(unsigned);
void LUDecompose();
SquareMatrix *Lptr, *Uptr, *Pptr; //should be initialized by LUDecompose before using
protected:
void validateData();
private:
};
#endif // SQUAREMATRIX_H
and I am trying to set Lptr, Uptr (and maybe Pptr) with a call to SquareMatrix::LUDecompose(). It is defined below:
void SquareMatrix::LUDecompose()
{
unsigned rowCount = this->getRowCount();
//initialize L to identityMatrix
*this->Lptr = SquareMatrix::identityMatrix(rowCount);
//initialize U to sparse matrix with the first row containing the sole non-zero elements
std::vector<std::vector<long double> > UData(1, this->matrixData[0]); //making first rowVector the first rowVector of this
UData.insert(UData.end(), rowCount - 1, std::vector<long double>(rowCount,0)); //making all other rowVectors zero vectors
*Uptr = SquareMatrix(UData);
// attempting to perform LU decomposition
for (unsigned j = 0; j < rowCount; j++)
{
long double pivot = Uptr->matrixData[j][j];
//the pivot should be non-zero; throwing exception that should effectively cause function to return
if (pivot == 0)
throw MatrixArithmeticException(LU_DECOMPOSITION_FAILURE);
for (unsigned k = j+1; k < rowCount; k++)
{
if (j == 0)
{
//using *this to compute entries for L,U
this->Lptr->matrixData[k][j] = (this->matrixData[k][j])/pivot; //setting columns of L
long double multiplier = this->Lptr->matrixData[k][j];
//setting row of U
for (unsigned l = k; l < rowCount; l++)
{
Uptr->matrixData[k][l] = (this->matrixData[k][l])-multiplier*(this->matrixData[0][l]);
}
}
else
{
//using U to compute entries for L,U
//same procedure as before
this->Lptr->matrixData[k][j] = (Uptr->matrixData[k][j])/pivot;
long double multiplier = this->Lptr->matrixData[k][j];
for (unsigned l = k; l < rowCount; l++)
{
Uptr->matrixData[k][l] -= multiplier*(Uptr->matrixData[0][l]);
}
}
}
}
}
Upon trying to test out this function, it throws a segmentation fault at me, with the last line being the first line where I attempt to manipulate Lptr.
I attempt to change the object pointed by Lptr, and I know that I will not be able to reference the function and set the pointer equal to that reference. In other words, my compiler (GNU GCC compiler) will not allow this->Lptr = &SquareMatrix::identityMatrix(rowCount); as it will throw an -fpermissive type error.
Note: SquareMatrix::identityMatrix(unsigned) is defined as:
SquareMatrix SquareMatrix::identityMatrix(unsigned size)
{
std::vector<long double> rowVector(size, 0L);
std::vector<std::vector<long double> > identityMatrixData;
for (int i = 0; i < size; i++)
{
//setting the rowVector to zero-one vector
rowVector[i] = 1L;
if (i > 0) rowVector[i-1] = 0L;
//pushing rowVector into identityMatrixData
identityMatrixData.push_back(rowVector);
}
return SquareMatrix(identityMatrixData);
}
What do you think you CAN do about it?
I think I have two options:
throw the object on the heap, and then try to set it with the function (that would seem useless as you are redefining the object you just defined by throwing it on the heap)
get c++11 (or something similar)
Make the function a helper function that returns a std::vector<SquareMatrix*> of size two (containing pointers to the two desired SquareMatrix values), and create a function that calls the helper function and sets Lptr, Uptr to the respective elements of the returned vector.
Are my options this limited??

*Uptr = SquareMatrix(UData); in LUDecompose() is the problem.
You cannot set the pointer to an object that is being destroyed when the function returns. Then the pointer is a dangling pointer and whenever you attempt to use it, it'll segfault.
You need to do Uptr = new SquareMatrix(UData);. Then in your destructor, call delete Uptr;.
If you have access to C++11, you can use std::unique_ptr or any pointer containers/wrappers.
Examples of your options:
#include <memory>
class Matrix
{
public:
Matrix() {}
virtual ~Matrix() {}
};
class SqMatrix : public Matrix //using raw pointers. You must remember to delete your pointers.
{
private:
SqMatrix* UPtr = nullptr;
public:
SqMatrix() : Matrix() {}
void InitPtrs() {delete UPtr; UPtr = new SqMatrix();}
~SqMatrix() {delete UPtr;}
};
class OMatrix : public Matrix //No need to worry about clean up.
{
private:
std::unique_ptr<OMatrix> OPtr;
public:
OMatrix() : Matrix() {}
void InitPtrs() {OPtr.reset(new OMatrix());}
~OMatrix() {}
};
Another option is to just store it in a vector.

Related

How to read data in private members of the class in main.cpp file?

I have a trouble with usage of private members of the class! I try to read and remember data into them in main.cpp file. I don't need to create any other values to remember read data. How to fix this problem and use them? I use <fstream> library to read data from file and remove them into ofstream file for output. I use .h files and .cpp files and main.cpp file.
Here is code in matrix.h file:
class Matrix
{
private:
int R; // amount of rows
int C; // amount of columns
double **mat; // pointer to two-dimensional array
public:
Matrix(); // default constructor
Matrix(Matrix &&) // move constructor
Matrix(int, int); // constructor with two parameters
double &ReturnReferenceToElement(int, int); // method to return reference to element of array
}
This is matrix.cpp file:
#include <iostream>
#include "matrix.h"
Matrix::Matrix()
{
R = 3;
C = 3;
mat = new double *[R];
for(int i = 0; i < R; i++)
{
mat[i] = new double [C];
}
}
Matrix::Matrix(Matrix &&M)
{
R = M.R;
C = M.C;
for(int i = 0; i < R; i++)
{
for(int j = 0; j < C; j++)
{
mat[i][j] = M.mat[i][j];
}
}
}
main.cpp:
#include <iostream>
#include <fstream>
#include "matrix.h"
using namespace std;
int main()
{
Matrix m;
ifstream in("in.txt");
ofstream out("out.txt");
in >> R >> C; // here I try to read data from file into private member
for(int k = 0; k < R; k++)
{
for(int s = 0; s < R; s++)
{
in >> mat[k][s]; // here I try to read into the private member
}
}
out << SumOfElements(**mat, R, C);
out << Averaged_Matrix(**mat, R, C);
return 0;
}
Functions SumOfElements() and Averaged_Matrix() are written in another file which is connected, and they work correctly.
Is it possible to use private members without setters and getters?
You're not allowed to access private fields from outside the containing class. But it looks like you have a constructor that takes R and C -- so read those fields then construct a Matrix object, passing R and C as arguments.
The idea of private methods is that you very specifically aren't supposed to touch them. So you can either add getters and setters, or you can reframe how you're trying to do what you're trying to do.
int r, c;
cin >> r >> c;
Matrix m(r, c);
If you ever feel the need to access private members of a class, then there's something terribly wrong. Either with the classes design, or in the way you want to interact with it.
In your particular case, the class design itself is ill conceived. In particular the problem attempted to be masked by declaring certain members private is, that altering them after construction will corrupt the classes behavior.
Your approach to this makes this is a XY problem: You think that you have to somehow deal with the access specifier, when in fact, the non-constness of members of the class that must not be altered is the cause of your troubles.
BTW: double **mat; does not make a 2D array. It makes an (1D) array of pointers to (1D) arrays of doubles. The two level indirection upon access will kill performance, not to speak of the high likelyhod that rows/columns of the matrix won't be contiguous in memory and thus will perform poorly due to cache misses and it being hard to prefetch.
A much better design for you class would look like this
#include <cstddef>
#include <cmath>
class Matrix
{
public:
typedef unsigned short dim_t;
dim_t const R; // amount of rows
dim_t const C; // amount of columns
double *const mat; // pointer to two-dimensional array
// NO DEFAULT CONSTRUCTOR!
// copy constructor
Matrix(Matrix const &m)
: R(m.R), C(m.R)
, mat(new double[(size_t)R * (size_t)C])
{
auto const N = (size_t)R * (size_t)C;
for(size_t i = 0; i < N; ++i){ mat[i] = m.mat[i]; }
}
// constructor with two parameters
Matrix(dim_t const r_, dim_t const c_)
: R(r_), C(c_)
, mat(new double[(size_t)R * (size_t)C])
{
auto const N = (size_t)R * (size_t)C;
for(size_t i = 0; i < N; ++i){ mat[i] = NAN; }
}
~Matrix(){ delete[] mat; }
// methods to return reference to element of
// !!! THOSE DO NOT PERFORM BOUNDS CHECKS!
double &operator()(dim_t const r, dim_t const c)
{ return mat[(size_t)R*(size_t)c + (size_t)r]; }
double const &operator()(dim_t const r, dim_t const c) const
{ return mat[(size_t)R*(size_t)c + (size_t)r]; }
};
Why is this better? First and foremost, by being declared const members of the struct, the need to "hide" them from the outside, that is protecting them from unintended alteration is gone; if one really want to be so hard pressed to alter those elements it can be done by forcing the compiler into undefined behavior, but the same methods would also allow to discard the access specifiers.
Thus where you feel the need to directly access elements of Matrix::mat you can do so, in relative safety. The compiler will forbid you to alter the
Now you might wonder why I declared a type for the dimensions that is unsigned short. The reason for this is, that on most relevant architectures and platforms out there (except 8 and 16 bit microcontrollers), the result of multiplication of the short will always fit into a size_t, so this prevents running into an integer overflow bug on allocation of the 2D array.
You can then use that like this:
#include <iostream>
#include <fstream>
#include "matrix.h"
int main()
{
std::ifstream in("in.txt");
Matrix::dim_t R, C;
in >> R >> C;
Matrix m(R,C);
for( Matrix::dim_t k = 0; k < m.R; k++ )
for( Matrix::dim_t s = 0; s < m.C; s++ ){
in >> m(k, s);
}
std::ofstream out("out.txt");
out << SumOfElements(m.mat, m.R, m.C);
out << Averaged_Matrix(m.mat, m.R, m.C);
return 0;
}

Multidimensional array: operator overloading

I have a class with a multidimensional array:
it is possible to create a one, two, ..., n dimensional array with this class
if the array has n dimensions, i want to use n operator[] to get an object:
example:
A a({2,2,2,2}];
a[0][1][1][0] = 5;
but array is not a vector of pointer which lead to other vectors etc...
so i want the operator[] to return a class object until the last dimension, then return a integer
This is a strongly simplified code, but it shows my problem:
The error i receive: "[Error] cannot convert 'A::B' to 'int' in initialization"
#include <cstddef> // nullptr_t, ptrdiff_t, size_t
#include <iostream> // cin, cout...
class A {
private:
static int* a;
public:
static int dimensions;
A(int i=0) {
dimensions = i;
a = new int[5];
for(int j=0; j<5; j++) a[j]=j;
};
class B{
public:
B operator[](std::ptrdiff_t);
};
class C: public B{
public:
int& operator[](std::ptrdiff_t);
};
B operator[](std::ptrdiff_t);
};
//int A::count = 0;
A::B A::operator[] (std::ptrdiff_t i) {
B res;
if (dimensions <= 1){
res = C();
}
else{
res = B();
}
dimensions--;
return res;
}
A::B A::B::operator[] (std::ptrdiff_t i){
B res;
if (dimensions <=1){
res = B();
}
else{
res = C();
}
dimensions--;
return res;
}
int& A::C::operator[](std::ptrdiff_t i){
return *(a+i);
}
int main(){
A* obj = new A(5);
int res = obj[1][1][1][1][1];
std::cout<< res << std::endl;
}
The operator[] is evaluated from left to right in obj[1][1]...[1], so obj[1] returns a B object. Suppose now you just have int res = obj[1], then you'll assign to a B object (or C object in the case of multiple invocations of []) an int, but there is no conversion from B or C to int. You probably need to write a conversion operator, like
operator int()
{
// convert to int here
}
for A, B and C, as overloaded operators are not inherited.
I got rid of your compiling error just by writing such operators for A and B (of course I have linking errors since there are un-defined functions).
Also, note that if you want to write something like obj[1][1]...[1] = 10, you need to overload operator=, as again there is no implicit conversion from int to A or your proxy objects.
Hope this makes sense.
PS: see also #Oncaphillis' comment!
vsoftco is totally right, you need to implement an overload operator if you want to actually access your elements. This is necessary if you want it to be dynamic, which is how you describe it. I actually thought this was an interesting problem, so I implemented what you described as a template. I think it works, but a few things might be slightly off. Here's the code:
template<typename T>
class nDimArray {
using thisT = nDimArray<T>;
T m_value;
std::vector<thisT*> m_children;
public:
nDimArray(std::vector<T> sizes) {
assert(sizes.size() != 0);
int thisSize = sizes[sizes.size() - 1];
sizes.pop_back();
m_children.resize(thisSize);
if(sizes.size() == 0) {
//initialize elements
for(auto &c : m_children) {
c = new nDimArray(T(0));
}
} else {
//initialize children
for(auto &c : m_children) {
c = new nDimArray(sizes);
}
}
}
~nDimArray() {
for(auto &c : m_children) {
delete c;
}
}
nDimArray<T> &operator[](const unsigned int index) {
assert(!isElement());
assert(index < m_children.size());
return *m_children[index];
}
//icky dynamic cast operators
operator T() {
assert(isElement());
return m_value;
}
T &operator=(T value) {
assert(isElement());
m_value = value;
return m_value;
}
private:
nDimArray(T value) {
m_value = value;
}
bool isElement() const {
return m_children.size() == 0;
}
//no implementation yet
nDimArray(const nDimArray&);
nDimArray&operator=(const nDimArray&);
};
The basic idea is that this class can either act as an array of arrays, or an element. That means that in fact an array of arrays COULD be an array of elements! When you want to get a value, it tries to cast it to an element, and if that doesn't work, it just throws an assertion error.
Hopefully it makes sense, and of course if you have any questions ask away! In fact, I hope you do ask because the scope of the problem you describe is greater than you probably think it is.
It could be fun to use a Russian-doll style template class for this.
// general template where 'd' indicates the number of dimensions of the container
// and 'n' indicates the length of each dimension
// with a bit more template magic, we could probably support each
// dimension being able to have it's own size
template<size_t d, size_t n>
class foo
{
private:
foo<d-1, n> data[n];
public:
foo<d-1, n>& operator[](std::ptrdiff_t x)
{
return data[x];
}
};
// a specialization for one dimension. n can still specify the length
template<size_t n>
class foo<1, n>
{
private:
int data[n];
public:
int& operator[](std::ptrdiff_t x)
{
return data[x];
}
};
int main(int argc, char** argv)
{
foo<3, 10> myFoo;
for(int i=0; i<10; ++i)
for(int j=0; j<10; ++j)
for(int k=0; k<10; ++k)
myFoo[i][j][k] = i*10000 + j*100 + k;
return myFoo[9][9][9]; // would be 090909 in this case
}
Each dimension keeps an array of previous-dimension elements. Dimension 1 uses the base specialization that tracks a 1D int array. Dimension 2 would then keep an array of one-dimentional arrays, D3 would have an array of two-dimensional arrays, etc. Then access looks the same as native multi-dimensional arrays. I'm using arrays inside the class in my example. This makes all the memory contiguous for the n-dimensional arrays, and doesn't require dynamic allocations inside the class. However, you could provide the same functionality with dynamic allocation as well.

Creating a derived class object inside of base class object

I'm implementing matrices according to the strategy pattern.
for that I have MyMatrix, which holds a pointer to Matrix, and two subclasses that inherit from Matrix - SparseMatrix & RegMatrix.
when adding two matrices, because I can't know which matrix I'm adding to which matrix, I implemented a base function which uses an inner method of each inheriting class, and when adding - I just add the new elements to the lefthand matrix.
This works fine.
my problem is - I now want to perform matrix multiplication.
I want to implement this method in the base class - Matrix.
this is what I have until now:
Matrix& multiple(Matrix &other)
{
double result = 0;
int newMatrixRowSize = getRowSize();
int newMatrixColSize = other.getColSize();
double *resultArray = new double[newMatrixRowSize*newMatrixColSize];
for (int i = 1; i <= getColSize(); i++)
{
for (int j = 1; j <= other.getColSize(); j++)
{
for (int k = 1; k <= other.getRowSize(); k++)
{
Pair firstPair(i,k);
Pair secondPair(k,j);
result += getValue(firstPair)*other.getValue(secondPair);
}
Pair resultIndex(i,j);
resultArray[getNumIndex(resultIndex, newMatrixRowSize, newMatrixColSize)] = result;
result = 0;
}
}
delete [] resultArray;
}
only problem is, now I can't just add the new elements to the lefthand matrix, I have to create a new RegMatrix or SparseMatrix, and according to the number of zeros in the matrix - swap to the legit representation of matrix.
so my question is - is it "legal" or good practice to create an instance of the base class' derived class inside the base class?
I want to avoid using the factory pattern, and more willing to do something polymorphic without knowing the kind of matrix in hand
You have to use a factory if you want to create objects of different types depending on condition. If you don't want Matrix to know about its descendants, you have several options. Apart from implementations using interfaces, in C++11 you can use std::function:
class Matrix {
typedef std::function<Matrix*(const double*, int, int)> Factory;
Factory factory;
public:
Matrix(const Factory& f) : factory(f) {}
Matrix* multiple(Matrix &other) {
....
return factory(resultArray, newMatrixRowSize, newMatrixColSize);
}
};
It gives you the advantage that you can pass any function-like object as a factory:
Matrix* matrixFactoryFunc(const double* data, int rowSize, int colSize) {
return nullptr;
}
class MatrixFactoryCallable {
public:
Matrix* operator()(const double* data, int rowSize, int colSize) {
return nullptr;
}
};
class MatrixFactoryWithMemFun {
public:
Matrix* createMatrix(const double* data, int rowSize, int colSize) {
}
};
void testFactory() {
std::function<Matrix*(const double*, int, int)> factory;
factory = matrixFactoryFunc;
factory = MatrixFactoryCallable();
MatrixFactoryWithMemFun mi;
factory = std::bind(&MatrixFactoryWithMemFun::createMatrix, &mi, _1, _2, _3);
Matrix m(factory);
}

C++ how to pass array of pointers to a function

I need to pass an array of pointers to a function,
In the example below, there is a class called base and an array of pointers called pool.
How can I pass the array pool to a function called function?
1) in case that I want to be able to change the original array of pointers.
2) in case that I only want to pass a copy of the array of pointers.
Thanks,
class base
{
};
void function (base * pool)
{
}
int main
{
base *pool[40];
function (pool[0]);
return 0;
}
class base
{
public:
int a;
};
void function (base ** pool)
{
for (int i = 0 ; i < 40; ++i)
cout<<pool[i]->a<<' ';
}
int main()
{
base *pool[40];
// Allocate 40 base objects and the 40 base pointers
// point to them respectively
for(int i = 0; i < 40; ++i)
{
pool[i] = new base;
pool[i]->a = i;
}
function (pool);
// free the 40 objects
for(int i = 0; i < 40; ++i)
delete pool[i];
return 0;
}
I added the a member just as an example.
Even better would be
void function (base ** pool, int n)
{
for (int i = 0 ; i < n; ++i)
cout<<pool[i]->a<<' ';
}
and
function (pool, n);
It's not so easy to pass a copy of the array - especially in the case where the objects itself are dynamically allocated.
To pass an array to a function, and maintain the type information about the array, you can use a template:
template <unsigned N>
void function (base *(&pool)[N]) {
}
There is no way to pass a copy of an array, unless it is inside a struct or class. In C++11, you have such a class in STL, called array:
#include <array>
template <unsigned N>
void function (std::array<base *, N> pool) {
pool[0] = 0;
}
base b;
std::array<base *, 40> p;
p[0] = &b;
function(p);
assert(p[0] == &b);

Elegant way for a recursive C++ template to do something different with the leaf class?

I have a C++ class template that makes an Array of pointers. This also gets typedefed to make Arrays of Arrays and so on:
typedef Array<Elem> ElemArray;
typedef Array<ElemArray> ElemArrayArray;
typedef Array<ElemArrayArray> ElemArrayArrayArray;
I would like to be able to set one leaf node from another by copying the pointer so they both refer to the same Elem.
But I also want to be able to set one Array (or Array of Arrays etc) from another. In this case I don't want to copy the pointers, I want to keep the arrays seperate and descend into each one until I get to the leaf node, at where I finally copy the pointers.
I have code that does this (below). When you set something in an Array it calls a CopyIn method to do the copying.
But because this is templated it also has to call the CopyIn method on the leaf class, which means I have to add a dummy method to every leaf class that just returns false.
I have also tried adding a flag to the template to tell it whether it contains Arrays or not, and so whether to call the CopyIn method. This works fine - the CopyIn method of the leaf nodes never gets called, but it still has to be there for the compile to work!
Is there a better way to do this?
#include <stdio.h>
class Elem {
public:
Elem(int v) : mI(v) {}
void Print() { printf("%d\n",mI); }
bool CopyIn(Elem *v) { return false; }
int mI;
};
template < typename T > class Array {
public:
Array(int size) : mB(0), mN(size) {
mB = new T* [size];
for (int i=0; i<mN; i++)
mB[i] = new T(mN);
}
~Array() {
for (int i=0; i<mN; i++)
delete mB[i];
delete [] mB;
}
T* Get(int i) { return mB[i]; }
void Set(int i, T* v) {
if (! mB[i]->CopyIn(v) ) {
// its not an array, so copy the pointer
mB[i] = v;
}
}
bool CopyIn(Array<T>* v) {
for (int i=0; i<mN; i++) {
if (v && i < v->mN ) {
if ( ! mB[i]->CopyIn( v->mB[i] )) {
// its not an array, so copy the pointer
mB[i] = v->mB[i];
}
}
else {
mB[i] = 0;
}
}
return true; // we did the copy, no need to copy pointer
}
void Print() {
for (int i=0; i<mN; i++) {
printf("[%d] ",i);
mB[i]->Print();
}
}
private:
T **mB;
int mN;
};
typedef Array<Elem> ElemArray;
typedef Array<ElemArray> ElemArrayArray;
typedef Array<ElemArrayArray> ElemArrayArrayArray;
int main () {
ElemArrayArrayArray* a = new ElemArrayArrayArray(2);
ElemArrayArrayArray* b = new ElemArrayArrayArray(3);
// In this case I need to copy the pointer to the Elem into the ElemArrayArray
a->Get(0)->Get(0)->Set(0, b->Get(0)->Get(0)->Get(0));
// in this case I need go down through a and b until I get the to Elems
// so I can copy the pointers
a->Set(1,b->Get(2));
b->Get(0)->Get(0)->Get(0)->mI = 42; // this will also set a[0,0,0]
b->Get(2)->Get(1)->Get(1)->mI = 96; // this will also set a[1,1,1]
// should be 42,2, 2,2, 3,3, 3,96
a->Print();
}
You could use template specialization to do something different with the leaf class:
template <> class Array<Elem> {
// Define how Array<Elem> should behave
}
As others mentioned in the comments, you should really consider using operator [] instead of Get and Set methods for array indexes.
I rearranged the code a bit to use template specialization, now the normal Set does a deep copy like this:
void Set(int i, T* v) { mB[i]->CopyIn(v); }
but for the array that contains the leaves you have to add the specialization:
template <> void Array<Elem>::Set(int i, Elem* v) { SetPtr(i,v); }
Of course you have to add a new one of these for every different leaf class. At least if you forget to do this you get a compiler error because it can't find CopyIn in the Elem class.
I thought about replacing CopyIn with an overloaded assignment operator, but this would loose the compile warning if you forgot to add the specialization.
I also thought about doing operator[] instead of Get and Set (just for this example), but it seems a bit dangerous with all these pointers flying around - it's easy to write a[0] instead of (*a)[0]. Also I couldn't work out the magic needed to convert the pointer in the Array into the correct sort of reference for [] to return (anyone know how to do that?).
#include <stdio.h>
class Elem {
public:
Elem(int v) : mI(v) {}
void Print() { printf("%d\n",mI); }
int mI;
};
template < typename T > class Array {
public:
Array(int size) : mB(0), mN(size) {
mB = new T* [size];
for (int i=0; i<mN; i++)
mB[i] = new T(mN);
}
~Array() {
for (int i=0; i<mN; i++)
delete mB[i];
delete [] mB;
}
T* Get(int i) { return (i<mN) ? mB[i] : 0; }
void Set(int i, T* v) { mB[i]->CopyIn(v); }
void SetPtr(int i, Elem* v) { mB[i] = v; }
bool CopyIn(Array<T>* v) {
for (int i=0; i<mN; i++) {
if (v && i < v->mN ) {
Set( i, v->Get(i) );
}
else {
mB[i] = 0;
}
}
}
void Print() {
for (int i=0; i<mN; i++) {
printf("[%d] ",i);
mB[i]->Print();
}
}
private:
T** mB;
int mN;
};
typedef Array<Elem> ElemArray;
typedef Array<ElemArray> ElemArrayArray;
typedef Array<ElemArrayArray> ElemArrayArrayArray;
template <> void Array<Elem>::Set(int i, Elem* v) { SetPtr(i,v); }
int main () {
ElemArrayArrayArray* a = new ElemArrayArrayArray(2);
ElemArrayArrayArray* b = new ElemArrayArrayArray(3);
// In this case I need to copy the pointer to the Elem into the ElemArrayArray
a->Get(0)->Get(0)->Set(0, b->Get(0)->Get(0)->Get(0));
// in this case I need go down through a and b until I get the to Elems
// so I can copy the pointers
a->Set(1,b->Get(2));
b->Get(0)->Get(0)->Get(0)->mI = 42; // this will also set a[0,0,0]
b->Get(2)->Get(1)->Get(1)->mI = 96; // this will also set a[1,1,1]
// should be 42,2, 2,2, 3,3, 3,96
a->Print();
}