How do I delete a pure virtual function inherited from base class?

Viewed 287

Let's say I have a base class called Human. Baby and Adult are sub-classes of Human. Human has a function run as a pure virtual function and I don't want Baby to inherit run but if I don't override run, Baby would become an abstract class.

class Human{
 public:
   // Some human attributes.
   virtual void run()=0;
};

class Adult: public Human{
 public:
   void run(){
      // Adult running function
   }
};

class Baby: public Human{
 public:
   void run()=delete; //error

   // If I don't override `run` then Baby is marked as an abstract class

   void crawl(){
     // Baby crawling function.
   }
};

Error if I mark run with =delete

prog.cpp:19:10: error: deleted function ‘virtual void Baby::run()’
     void run()=delete;
          ^~~
prog.cpp:6:22: error: overriding non-deleted function ‘virtual void Human::run()’
         virtual void run()=0;
                      ^~~

Might be a bad example but what I want is to inherit everything except for run in Baby. Is it possible?


Disclaimer: I'm not implementing it anywhere. Just out of curiosity.

1 Answers

This is not possible. Consider the following code:

Human *CreateAPerson() {
  return new Baby();
}

int main() {
  Human *human = CreateAPerson();
  human->run();
}

The compiler would have no way to know that human->run() is illegal.

Related