M
mlimber
Michael said:Hello,
I want to use an object (LowCut) within another object (SampleRateConverter)
like it is written as follows:
class SampleRateConverter
{
public:
SampleRateConverter( int iSourceSampleRate, int iTargetSampleRate )
{
LowCut = LowPassFilter(dCutoff, 512, BLACKMAN); // here
debugger calls first constructor and then destructor ~LowPassFilter
}
private:
LowPassFilter LowCut;
void doSomething();
};
I used the debugger and realized:
After calling the constructor for LowPassFilter within SampleRateConverter,
the destructor of LowPassFilter is called automatically.
That means, the Filter becomes destroyed immediately. So, I cannot use it in
the method doSomething. The Filter allocates a buffer in memory for storing
information.
But using LowPassFilter *LowCut; (pointer) (instead of the version written
above) and creating the Filter with new-operator (new LowPassFilter(..)) it
works?
Then I have to delete this Filter manually by calling delete LowCut.
But why I cannot use the first version? Why does the runtime environment
destroys the Filter object immediately after generating it?
Anything wrong due to OOP design issues?
Kind regards, Michael
Try using an initialization list instead:
class SampleRateConverter
{
public:
SampleRateConverter( int iSourceSampleRate, int iTargetSampleRate
)
: LowCut( LowPassFilter(dCutoff, 512, BLACKMAN) )
{}
// ...
};
See the FAQ:
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6
Cheers! --M