Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if C++ abstract method is defined at runtime

How to check if C++ abstract method is defined at runtime

class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();

This gives error.

Thanks, Max

like image 745
Max Avatar asked Nov 27 '22 15:11

Max


2 Answers

As you can't instantiate an abstract class, any class you encounter at runtime will not have any pure virtual methods (unless you're in a constructor or destructor at the time), they'll all have been overriden with a non-pure overrider. There is nothing to check.

like image 124
CB Bailey Avatar answered Dec 05 '22 15:12

CB Bailey


An abstract method must be implemented in order for the class to be instantiated. There's no such thing as checking whether a method is implemented, the compiler will do this for you. In this case, you can't have a CBase object because it has abstract methods.

like image 45
Jeff Foster Avatar answered Dec 05 '22 14:12

Jeff Foster