Ok hopefully this question is not duplicate as I haven't found it. As the title suggests I want to have an abstract class with, say, two subclasses. I then want to be able to create an object from this abstract class with a constructor the automatically chooses the appropriate subclass to actually create. I am not sure if this is possible, but it seems that it would be useful. For example consider the following code snippet:
#ifndef ELEMENT_H
#define ELEMENT_H
class Element
{
public:
int Type;
int* nodes;
double* xpts;
double* ypts;
double* zpts;
public: Element(int typ)
{
Type = typ;
if(typ==2) //linear 2D triangles
{
nodes = new int[3];
xpts = new double[3];
ypts = new double[3];
zpts = new double[3];
}
else if(typ==3) //linear 2D quadrangles
{
nodes = new int[4];
xpts = new double[4];
ypts = new double[4];
zpts = new double[4];
}
}
virtual int stiffnessMatrix() = 0;
virtual int massMatrix() = 0;
};
class TriLin2D : public Element
{
public:
double kmat[3][3];
double mmat[3][3];
double lvec[3];
virtual int stiffnessMatrix();
virtual int massMatrix();
public: TriLin2D(int typ) : Element(typ){}
};
class SqrLin2D : public Element
{
public:
double kmat[4][4];
double mmat[4][4];
double lvec[4];
virtual int stiffnessMatrix();
virtual int massMatrix();
public: SqrLin2D(int typ) : Element(typ){}
};
#endif
So this is what I have so far. If I want to create and object I would then do something like:
int Type=2;
TriLin2D e(Type); //creates a TriLin2D object
or
int Type 3;
SqrLin2D e(Type); //creates a SqrLin2D object
What I want though is to be able to do something like:
int Type=2;
Element e(Type); //automatically creates an TriLin2D object based on constructor input
or
int Type=3;
Element e(Type); //automatically creates a SqrLin2D object based on constructor input
Hopefully you can see why this would be useful. Now I dont have to manually change the element subclasses (i.e. TriLin2D or SqrLin2D), but instead just change the Type passed to the constructor. I'm not sure if this is possible, and if it is possible, how do I do something like this? Thanks.
Note: I am new to C++ so feel free to make comments on my coding style.