I have two classes B and C (both derived from a class A) a class called H which holds either A or B.
Code :
class A // abstract base class
{
// bells and whistles
// virtual fn
void fn() = 0 ;
protected:
// some variables common to B and C
};
class B : public A // inherit from A...
{
B();
fn(); // implement virtual function
// bells and whistles
};
B::B() :A()
{
// things
}
void B::fn()
{
// things
}
// Class C : exactly the same as class B
// Class H : holds B or C
enum class CLASS_TYPE { TYPE_B, TYPE_C }
class H
{
public:
H(CLASS_TYPE type_);
~H();
private:
A * _obj;
};
H::H(CLASS_TYPE type_)
{
switch(type_)
{
case CLASS_TYPE::B:
_obj = new B();
break;
case CLASS_TYPE::C:
_obj = new C();
break;
}
}
H::~H()
{
delete _obj;// delete allocated object
}
Is this the right way to create an internal object within a class based on arguments in a constructor ? Also is using abstract base class , virtual efficient ? This is part of a large scale simulation program , and I would like to avoid performance penalties.
Thank you. PS: I have tried to keep things simple, if there is any more information required please tell.