I have 5 classes. A father class, which would be Cell. It has a virtual method, called char symbol(void), which returns the char 'X'. It has four son classes : CellA, CellB, CellC and CellD, which respectively return 'A','B','C' and 'D' in their char symbol(void).
I want to overload the << operator to generically print any of these Cells. My attempt is the source included, however, i only get it to print 'X'.
That doesn't work.
(EDIT: I MEANT THAT DIDN'T SOLVE THE PROBLEMI hope you don't get me wrong, Bazzy)
Here's the code of the relevant methods
Have in mind, each class has its own .cpp and .hpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Cell {
//other stuff
public:
virtualchar symbol(void) const {return'X';}
// ...
};
//... in other .hpp file
class CellA : public Cell {
public:
//...
virtualchar symbol(void) const {return'A';}
//...
};
//code for Cells B, C & D is identical, changing 'A' to 'B''C','D'
I've tried it in two different ways: one the hand, everything in a main.cpp and on the other hand, I wrote .cpp/.hpp for each class.
The two ways worked great. Is there any detail you'd omitted?
Just one point: do not except that you'd have any optimization related to the inlining as your function is virtual. The two concepts are, by nature, totally not compatible.
Yeah, it works. Thanks DavyB and player6 for testing it out!!, and Bazzy for the shorter version of the ostream cout code.
I realized where the problem was
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Board {
private:
Cell*** base_ ; // Its a [0 to dim_x-1][0 to dim_y-1] array of Cell (father) pointers
unsigned dim_x, dim_y;
public:
~Board(void);
Board(constunsigned& x, constunsigned& y);
void update(void);
//The problem was here
Cell* access(constunsigned& x, constunsigned& y) const;
// The function used to return Cell, instead of Cell*. In the old version, when the board
// returned *base_[x][y], the function returned a copy to the father Cell contained
// on the Cell that base_[x][y] pointed to (which could be CellA, CellB, CellC or CellD ) .
// That explains the strange behaviour
unsigned X (void) const; //returns dim x
unsigned Y (void) const; // returns dim y
};