SparksH
SparksH

Reputation: 1

C++ Create derived class with abstract base class method

I'm trying to create an abstract base class, BaseClass, which has some fields (but not all), that are included in the derived classes, DerivedClass1 and DerivedClass2.

BaseClass.h

class BaseClass
{
private:
    int bmember1;
    int bmember2;

public:
    BaseClass();
    ~BaseClass();
};

For example, DerivedClass1 would not have additional members...

DerivedClass1.h

class DerivedClass1 : public BaseClass
{
public:
    DerivedClass1();
    ~DerivedClass1();
};

... but DerivedClass2 would, dmember1 and dmember2.

DerivedClass2.h

class DerivedClass2 : public BaseClass
{
private:
    int dmember1;
    int dmember2;

public:
    DerivedClass1();
    ~DerivedClass1();
};

Now, I want some method in BaseClass that I could construct either derived class with, dynamically, using something arbitrary, such as an Enum:

SwitchEnum.h

enum Switch_Enum
{
    DERIVED_1,
    DERIVED_2
};

I want to use parameters to initialize the fields in the BaseClass with, but I also want to give some default value to the ones present only in the derived classes, that I can later change with a method, again, called from the BaseClass. So, something like

//(BaseClass.h)

//BaseClass constructor, initializingthe BaseClass's fields with the parameters
BaseClass(int param1, int param2)
{
    //params to bmembers
}

//Construct the appropriate derived class
static BaseClass* createBase(int param1, int param2, Switch_Enum selector);
{
    switch(selector):
    {
    //DerivedClass1 if DERIVED_1, 2 if 2, etc. 
    //use BaseClass(int param1, int param2) to set the BaseClass fields that are present in all derived classes
    //If derived class has additional fields, give default values to those as well
    }
}

And finally, to set the possible additional fields, do something like:

//(BaseClass.h)
virtual void changeDmembers(int dmember2val, int dmember2val)
{
    //if DerivedClass1, do nothing
    //if DerivedClass2, set dmember1&2 to dmember1&2val
}

Do you think this is at all feasible? Should I approach this differently? Should I have all possible fields already appear in the BaseClass and only use them in the derived classes that would have them (which doesn't seem too elegant to me)?

Thank you kindly in advance!

Upvotes: 0

Views: 223

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Do you think this is at all feasible?

Yes.

Should I approach this differently?

Most certainly. Look up the factory pattern using your favorite search engine.

Should I have all possible fields already appear in the BaseClass and only use them in the derived classes that would have them (which doesn't seem too elegant to me)?

Your hunch is correct. That's not a good idea. A base class should not make any assumptions about classes derived from it. It should have exactly what it needs -- nothing less, nothing more.

Upvotes: 3

Related Questions