Hi all,
I am currently working on a large software project for scientific computing for my PhD research.
I am working on the architecture for part of the project now, and I am struggling with how to working with a polymorphic pointer as a function input parameter, by reference.
The following pseudo-code illustrates what I am trying to achieve:
class BaseClass
{
protected:
double parameter;
};
class DerivedClass : public BaseClass
{
};
class SecondDerivedClass : public BaseClass
{
};
class AnotherClass
{
public:
void setParameterOfDerivedClass( BaseClass*& baseClass, double& parameterValue );
};
int main
{
// Create instance of DerivedClass
DerivedClass myDerivedClass;
DerivedClass* pointerToMyDerivedClass;
// Set pointer to derived class to address of myDerivedClass
pointerToMyDerivedClass = &myDerivedClass;
// Create instance of AnotherClass
AnotherClass myAnotherClass;
// Set parameter through AnotherClass, for object of DerivedClass
myAnotherClass.setParameterOfDerivedClass( myDerivedClass, 10.0 );
myAnotherClass.setParameterOfDerivedClass( pointerToMyDerivedClass, 10.0 );
return 0;
};
The issue I am having is that for the function protype for setParameterOfDerivedClass() I want to use a polymorphic pointer to be able to pass objects of DerivedClass and SecondDerivedClass as the first argument of the function. For this I have defined the first argument as being of type BaseClass* and passed this as reference.
The user interface however now requires the function call:
myAnotherClass.setParameterOfDerivedClass( pointerToMyDerivedClass, 10.0 );
However, I want the user interface to be such that the user doesn't have to create a pointer to pass as function argument, but rather just pass the object itself, as:
myAnotherClass.setParameterOfDerivedClass( myDerivedClass, 10.0 );
Can I write my function prototype such that it accepts all derived classes of BaseClass as the first argument, without the user having to pass a pointer to that object?
Another question I have is related to the fact that AnotherClass needs access to the protected member variable parameter in BaseClass. Do I make AnotherClass a friend of BaseClass to achieve this? How do I implement this the best?
If there's a totally different and better way to achieve what I am trying to achieve, I am also open to suggestions.
I guess I can also overload the setParameterOfDerivedClass() for each derived class of base class, but I'm trying to avoid doing that by using the polymorphic pointer.
Any feedback would be greatly appreciated.
Thanks!
Kartik