Here are some things I've been asked to review.
There are two very distinct approaches. In the FAQ for A2 you were shown how to manipulate a one-dimensional array of size n*n as a two-dimensional array. This approach has the advantage that it uses fewer calls to malloc (or new), but it leaves the programmer with the responsibility for working out the array indexing arithmetic -- A[i][j] is represented as A[i*n +j]. This becomes even more detailed as you extend to higher dimensions (you might want to experiment with how you'd created a three-dimensional dynamic array).
A different approach is to make your two-dimensional array an array of pointers. This involves more calls to malloc or new, but it may seem more natural to the programmer, and extends simply to higher dimensions. It also allows you to have rows of different lengths, which might be suitable for, say, Pascal's Triangle or an array of strings (i.e., a two-dimensional array of char). Here's some example code:
int **buildTable(int n) { int **table = new int*[n]; for (int i = 0; i < n; i++) { table[i] = new int[n]; for (int j = 0; j < n; j++) table[i][j] = 7; } return table; } int **Pascal(int n) { int **table = new int*[n]; for (int i = 0; i < n; i++) { table[i] = new int[i+1]; /* row i has i+1 elements */ table[i][0] = 1; table[i][i] = 1; for (int j = 1; j < i; j++) table[i][j] = table[i-1][j-1] + table[i-1][j]; } return table; } int *buildTable2(int n) { int *table = new int[n*n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) table[i*n + j] = 7; } return table; } int main() { int **p = Pascal(5); for (int i = 0; i < 5; i++) { for (int j = 0; j < i+1; j++) printf("%d\t", p[i][j]); printf("\n"); } return 0; }
It depends. A function of the same name in the derived class hides
the function in the base class, even if the signatures
(e.g. parameter list) differ. You can refer explicitly to the base
classes version by using ::
(the namespace operator). A
reference to the base class will look for a match only there, unless you
modify the function with virtual. Here is some code that
illustrates some of this behaviour (you should experiment with
examples of your own):
#include <stdio.h> class A { public: void func1(int i); virtual void func2(int i); }; void A::func1(int i) { printf("func1 in A\n"); } void A::func2(int i) { printf("func2 in A\n"); } class B : public A { public: void func1(int i, int j); void func2(int i); }; void B::func1(int i, int j) { printf("func1 in B\n"); } void B::func2(int i) { printf("func2 in B\n"); } int main() { A a, *ap; B b, *bp; a.func1(1); b.func1(1,2); /* b.func(1) won't work--- no matching signature */ b.A::func1(1); a = b; a.func1(1); /* a.func1(1,2); can't find this signature in A */ ap = &b; bp = &b; ap->func1(1); /* ap->func1(1,2); can't find this signature in A */ ap->func2(1); a.func2(1); /* calls base class version */ /* bp->func1(1); can't find this signature in B */ bp->func1(1,2); return 0; }