I was wondering if there was a way to include a data member which is an array of unfixed size.
The function initModulation will create an int array of size M and a Complex array of size M. (Complex is another class and is made up of a real component and imaginary component).
The function modulate will need to be able to access these two arrays. These two arrays go out of scope after the init Modulation function is called. To avoid this, I would just make these two data members of the Modulator class, however I can't do that because the array size depends on M.
class Modulator
{
int M;
double phase;
std::string mapping;
public:
void initModulation(int M, double phase, std::string mapping);
double* modulate(int *input,int inputlength,int complexFlag);
};
Any ideas around this?
Thanks, Minh
You can use the
std::vector
class, which is like an array but has a variable size and requires no explicit memory management. If you declare one as a data member, then you can haveinitModulation
fill it with as many elements as it likes, but then have the data available inmodulate
.One suggestion - it might be a good idea to change
initModulation
to be a class constructor. That way, it gets called automatically and there's no risk of callingmodulate
without first initializing the object.I was wondering if there was a way to include a data member which is an array of unfixed size.
STL is probably what you are looking for.(
std::vector
...Don't write initialization functions without very special circumstances; construct with the constructor.
The arrays are logical part of the class data, since they are used for modulation, and that's what instances of the class do. So you should have them as members.
You were planning to create arrays of unknown-at-compile-time size, right? How does it matter whether you're storing them as members of the class or not? Either way, you have the information about M at this point, and use it accordingly.
But you shouldn't be allocating your own arrays, anyway. Use
std::vector
. After all, you're smart enough to usestd::string
for text data, so...Why would you use an
int
for a parameter that's supposedly some sort of "flag"? C++ has a real boolean type, calledbool
. Use it.For the input and output of modulation, again, use vectors.
Having a class with a member function whose name aligns with the class name is suspicious. Many languages support the idea of a "callable" object and C++ is among them. In C++, we spell this functionality "
operator()
".Thus:
Welcome to modern C++. :)