Reputation: 7121
I have two classes:
class A
class B: class A
I want to create a matrix that each pointer point to B (mat of 1X2).
so I defined:
A **mat;
mat = new A*[1];
*mat = new B[2]; // call the constructor.
now I have 2 elements: mat[0][0], mat[0][1].
mat[0][0] is initialized but mat[0][1] is NULL.
please help.
Upvotes: 0
Views: 110
Reputation: 170055
If sizeof(A) < sizeof(B)
than an array of A
's is not equivalent to an array of B
's.
Since in the second allocation you allocate concreete objects which are larger than what *mat
is supposed to point to, when you access the second element it doesn't access the second B
element, but rather slices into the first.
That's my guess anyway, since you didn't tell us much about A
and B
.
EDIT
To answer your comment, I'd start by limiting the amount of raw pointers you use. Use a vector of vectors instead. Each element of the vector can be a raw pointer to an A
. Which can have a run-time type of B
or C
.
#include <vector>
std::vector<std::vector<A*> > mat(1, std::vector<A*>(2, (A*)0));
Upvotes: 1
Reputation: 10660
If you need pointers to B, you don't need to specify anything about A. Since B derives A, you only have to allocate space for the larger one (B in this case).
For a matrix of pointers, you will need the following.
B *** mat;
mat = new B**[1]; //Dimension 1
mat[0] = new B*[2]; //Dimension 2 (array of pointers)
mat[0][0] = new B(); //Allocate B in [0][0]
mat[0][1] = new B(); //Allocate B in [0][1]
But if you know it will always be 1x2, just use the following:
B * mat[1][2];
Upvotes: 1