Reputation: 4213
I'm trying to have a base class with an array that the derived classes should set. The application is a tetris game, so I'd like to have a BaseShape class that holds an array of rotations that each derived class (i.e. SquareShape, TShape, etc) will set based on the rotations of the specific shape.
class BaseShape
{
public:
BaseShape();
BaseShape(int my_rot[4][5][5]);
~BaseShape();
int rot[4][5][5];
int i_rot;
};
class SquareShape : public BaseShape
{
public:
SquareShape();
~SquareShape();
};
I'd want to set the values for the rot member in the SquareShape class. I've tried several things such as assigning it in the derived class' constructor (then learned that you cannot assign arrays), setting it in SquareShape initializer list (then learned that you cannot initialize a base class' member in the derived class' initializer), and passing an array to the base class constructor and initializing the member to the parameter, which fails to compile with the error:
error: invalid conversion from ‘int (*)[5][5]’ to ‘int’ [-fpermissive]
rot{my_rot}
So I'm wondering if there is actually a way to achieve this or if there is a much simpler way to go about it.
Upvotes: 0
Views: 48
Reputation: 217428
C-arrays are not copyable, you might use std::array
instead
using Rot = std::array<std::array<std::array<int, 5>, 5>, 4>;
class BaseShape
{
public:
BaseShape();
BaseShape(Rot my_rot) : rot(my_rot) {}
~BaseShape();
Rot rot;
int i_rot = 0;
};
Upvotes: 1
Reputation: 122516
then learned that you cannot initialize a base class' member in the derived class' initializer
... stricly speaking thats true, but instead of initializing the class member directly you may call an appropriate constructor:
#include <iostream>
struct Base {
int x;
Base(int a) : x(a) {}
};
struct Foo : Base {
Foo(int a) : Base(a) {}
};
int main() {
Foo f(1);
std::cout << f.x << "\n";
}
on purpose I used an example without an array, because once you use std::array
or std::vector
, the arrayness wont be a problem anymore.
Upvotes: 1