Check at runtime if I can or cannot instantiate (abstract) class

Let's say I have:

class A:
{
public:
A();
virtual void foo();
};

class B:public A
{
public:
B();
void foo();
};

class C:public A
{
public:
C();
void foo();
};

and in main

if(is_abstract<A>::value==false)
{
   int option;
   cout<<"What type of object do you want to create? 0-A,1-B,2-C";
   cin option;
   if(option==0)
      A *a = new A();
   if(option==1)
      B *b = new B();
   else
      C *c = new C();
}
else
{
   int option;
   cout<<"What type of object do you want to create? 1-B,2-C";
   cin option;
   if(option==1)
      B *b = new B();
   else
      C *c = new C();
}

In the current state, the code would work. If I make virtual void foo()=0, A becomes abstract class and I get compile-time error because I cant instantiate abstract class at A *a = new A(). Is there a way to bypass this compile-time error? Thanks

Upvotes: 0

Views: 108

Answers (1)

SergeyA
SergeyA

Reputation: 62603

In the current form, code which tries to instantiate A will be generated (although never called). Even if compiler will not generate the code due to optimization, the non-generated code still has to be valid, and yours is not.

To work around it, you will have to employ some form of SFINAE to make sure the code which tries to instantiate A is never generated. Something like this:

void make(std::enable_if_t<std::is_abstract<A>::value>* = nullptr) {
   ... (the code which never creates A)
}

void make(std::enable_if_t<!std::is_abstract<A>::value>* = nullptr) {
   ... (the code which does create A)
}

...
make();

Upvotes: 2

Related Questions