Assume you define a class to contain another class, which in turn contains *another* class. During construction of the top-level class (if possible) you'd like to set an attribute of the lowest class.
So:
class Reg {int i1, i2, i3;}
class Cell (Reg a, b, c, d;}
class Filter (Cell[32]}
When I create an instance of filter, I'd like to pass an argument that will set i1, for example. How best to do this?
class Reg
{
int i1, i2, i3;
Reg ( int a = 0, int b = 0, int c = 0 ) : i1 ( a ), i2 ( b ), i3 ( c ) {} // notice: you can use the same name for members and constructor parameters
};
class Cell
{
Cell () : a ( 1,2,3 ), b ( 4, 5 ), c ( 6 ) {}
};
So, I create a Filter, passing the Reg value as a parameter. In the Filter constructor, since the Cells (and Regs) are created implicitly, how do I pass the Reg value down?
If you use a vector instead of an array, you'll have all your problem solved since you can call the vector constructor with a specified value.
Built-in array are not very flexible
I'm not familiar with vectors, but I did a little reading, and I don't see how this addresses the problem.
Again, if I have an object a which contains another object b, which contains another object c, and I want to set a value within c, but do so from the scope of a...is this possible at the time of construction? Or, do I need a set function?
If you have a vector, you can construct it like so: cell ( 32, Cell ( foo ) )
where
cell is the name of the vector,
32 is it's size
Cell ( foo ) is the Cell constructor
foo would be an appropriate list of parameters to pass to the constructor, which depends on how you implemented the constructor
At the risk of drifting slightly off-topic, I've tried to experiment with vectors in my code, and the compiler objected. Here's what I did in a header file:
1 2 3 4 5
#include <vector>
class Filter {
vector<Cell> cellArray(NBR_CELLS);
etc.
}
The compiler said:
error: ISO C++ forbids declaration of 'vector' with no type
error: expected ';' before '<' token
Thanks. I put "using namespace std;" earlier in the file, and I seem to have gotten past that problem.
NOW I get an error: NBR_CELLS is not a type. I have NBR_CELLS defined as a const int. This has me confused: doesn't the compiler expect the size of the vector here, and not a type?
This compiles and runs, but my initialization isn't working right. If this looks right to you, though, I'll just keep inspecting the lower-level constructors.
OK, I have another question regarding the constructor. if NBR_CELLS = 32, for example, do I need 32 instances of the Cell(rv) in order to initialize each element in the vector? In other words:
The vector constructor cellArray(NBR_CELLS, Cell(rv)) will
create NBR_CELLS amount of elements - all of these cells will be constructed identically
(in this case using the Cell(rv) constructor)
You don't write a seperate constructor for each element - (you can't anyway because the compiler will throw it out)