Originally Posted by
Elysia
You can't do that. If you define a variable with the same name in a derived class, it will only hide the one in the base class (read: there will be two variables named the same name, but the derived can only access its own variable and the base can still access its own). So there will be two variables with different dimensions but same name.
So, there's one thing I'm already doing wrong...
I will post the compilable code I made to help others understand my problem:
Code:
//base.h
class base{
public:
virtual void createArray();
protected:
int array[3][3];
};
Code:
//derived.h
#include "base.h"
class derived:public base{
private:
int array[3][3];
};
Code:
//derived.cpp
#include "derived.h"
#include <iostream>
void base::createArray(){
int temp[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
this->array[i][j] = temp[i][j];
}
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
std::cout << this->array[i][j] << ' ';
}
}
std::cout << std::endl;
}
Code:
//main.cpp
#include <iostream>
#include "derived.h"
derived *test = new derived();
int main()
{
test->createArray();
}
This code runs just fine. Although I think I made myself clear in my last post, I'd like to point some things out:
1) The dimension "3" in the derived class is just an example. Every derived class can have this dimension different from one another.
2) The dimension "3" in the base class is only there in order to match the dimension in the derived class and make this example code run.
So there you go, I don't know for sure what the dimension will be when I declare private: int array[x][y] in the base class, how can I use dynamically allocated arrays in this situation? Considering what Elysia said, it's worthless declare array AGAIN in the derived class, but as I said before, it is the derived class that actually have those dimensions...
Maybe this has an easy, simple solution, but as I said, I'm new to C++...
PS: I actually have a good reason not to use vectors and that's why I'm insisting on arrays.