pablo_worker pablo_worker - 21 days ago 7
C++ Question

How to avoid the issue of not being able to instantiate an abstract class

I have the following problem working with a library (it is the hdf5 library, but it doesn't matter).

I would like to do something like the following, but I think I can't because the Base class is abstract. In other words, I can't have late binding because I can't instantiate an object of an abstract class.

I have an abstract class and 2 derived classes. The code of main() is not correct because I can't do Base theObject;

//An abstract class
class Base
{
protected:
Base() {}
public:
void doSomething() = 0;
};

class DerivedA : public Base
{
public:
DerivedA() : Base() {}
void doSomething() {cout << "I am a DerivedA" << endl;}
};

class DerivedB : public Base
{
public:
DerivedB() : Base() {}
void doSomething() {cout << "I am a DerivedB" << endl;}
};


int main()
{
// A special function returns the type of object that it is placed at "thePath".
int theType = someSpecialFunction(thePath);
Base theObject; //This is not possible.
switch (theType)
{
case 1: //A derivedA object
{
theObject = openObjectOfTypeA(thePath); //Special function of the library.
break;
}
case 2: //A derivedB object
{
theObject = openObjectOfTypeB(thePath); //Special function of the library
break;
}
}

theObject.doSomething();
//whatever
}


I can do something like the following. However, in a real scenario I would end with a lot of repeated code.

int main()
{
// A special function returns the type of object that it is placed at "thePath"
int theType = someSpecialFunction(thePath);
switch (theType)
{
case 1: //A derivedA object
{
DerivedA theObject = openObjectOfTypeA(thePath);
theObject.doSomething();
break;
}
case 2: //A derivedB object
{
DerivedB theObject = openObjectOfTypeB(thePath);
theObject.doSomething();
break;
}
}
//whatever
}


Is there any method to avoid my "solution"?
Thank you in advance.

P0W P0W
Answer

You can have

Base* theObject;

And use the pointer to call member function . You will have to change return type of openObjectOfTypeA/B to return a pointer to Base class.

theObject->doSomething();

Comments