Hi,
I am doing too much coding with MFC, thus I have kind of forgotten some real object coding with C++. I have a little question about polymorphism with the new operator:
Say I have these three classes:
I want to do something like this:Code:class A {...}; //this is a pure virtual class class A1: public A {...}; class A2 : public A {...};
I don't know before hand what derived type of A the parameter will be, but I must create a new object of this type. The definitions of the classes have no real importance. The only solution I have so far is to have an attribute in A that gives the sub type (initialized in the Ctor, cannot be modified). Then I check on this type to make the proper new:Code:BOOL my_function(A param) { //A* m_pA m_pA = new ???; *m_pA = param; }
What's the "correct or best" "OO or C++" solution for that?Code:switch( param.type) { case type_1: m_pA = new A1; break; case type_2: m_pA = new A2; break; }
I would have another solution using a static function as an object factory...




Reply With Quote