I have the following code where I want to declare an object inside an IF statement. I understand that just declaring it inside an IF means that it’s outside the scope of the rest of the program. So I think I need to use a pointer.
My problem is that the classes that I want the user to choose from are derived from a base class. So I figured I probably need to create a pointer based on this base class… That sound about right?
See below for what I’m try to do, am I in the right ball park?
//create a stereo input object
StereoImage SO;
SO.open(File1,File2);
int StereoOption;
if (counter == 0) StereoOption = 1;
//think i need to create a pointer to the base class
SVAlgorithm *ptrSter;
//choose which method to use in stereo processing and set the base class pointer to derrived class
if (StereoOption == 1) {SVOpenCVBlockMatching DoStereo; cout << "Using option 1" << endl; *ptrSter = DoStereo;}
else if (StereoOption == 2) {SVOpenCVSemiGlobalBlockMatching DoStereo; cout << "Using option 2" << endl; *ptrSter = DoStereo;}
else if (StereoOption == 3) {SVNoMD DoStereo; cout << "Using option 3" << endl; *ptrSter = DoStereo;}
else if (StereoOption == 4) {SVCross DoStereo; cout << "Using option 4" << endl; *ptrSter = DoStereo;}
else if (StereoOption == 5) {SVAdaptDP DoStereo; cout << "Using option 5" << endl; *ptrSter = DoStereo;}
//set create DoStereo from the pointer
SVAlgorithm &DoStereo = *ptrSter;
//output matrix
Mat_<short> DispOut;
//load the disparity method params, compute it and show - works
DoStereo.loadParams();
DoStereo.compute(SO.getRawFrame(0),SO.getRawFrame(1),DispOut);
imshow("Disparity Map", DispOut*255);
The following classes are all derived from the class SVAlgorithm…
SVOpenCVBlockMatching,
SVOpenCVSemiGlobalBlockMatching,
SVNoMD,
SVCross,
SVAdaptDP.
No, your code is wrong. Pointer has absolutely no effect on object lifetime.
So this line
SVAlgorithm &DoStereo = *ptrSter;gives you Undefined Behavior because you try to dereference the pointer to destroyed object.Another possible problem is uninitialized
ptrSterandStereoOptionvariables. Looks like here is possible case whenptrSterwill not be assigned with proper object and its dereference will lead to UB too.You need to use dynamic storage with
newstatement and store result in some pointer. It’s highly recommended to use smart pointer instead of raw for this purpose, e.g.std::auto_ptrfor C++03 orstd::unique_ptrfor C++11.Example: