Search code examples
c++functionclassexceptionparent

C++ Determine which child class is calling a parent function


Alright so I couldn't find the answer anywhere, and this is my first post so please be kind. Basically i need to have an exception thrown if a certain child class calls a parent function under certain conditions, but another child class should always be able to execute the function.

--If you're wondering, its a withdraw function for an account class with savings and checkings child classes. Savings has a minimum balance (throw exception if withdraw causes it to go below minimum value) but checking has no minimum

class parent {
      public:

      int b;
      void A(){
             //1. Throws exception if b < # ONLY when child1 calls
             //2. Always executes code if child2 calls regardless of condition
      }              
}           


class child1 : public parent {
}

class child2 : public parent {
}


int main(){

    child1 one;
    child2 two;

    one.A();        //This needs to throw exception under certain conditions
    two.A();        //This will always execute
}

Anyone have any tips how to determine which child class is calling the function?


Solution

  • Because you don't have any virtual functions in the base class, you are just out of luck. Otherwise you could get the typeid of the actual class using: typeid *this

    Anyway, your function should be virtual in the base class and overridden in the child classes. Please remember: inheritance models an is-a relationship, so restricting service for specific child-classes goes against it's intended use. Better have the restricted behavior for the base class, and allow more in some child classes.