Search code examples
c++classconstructormember-initialization

Execute checks before initialization list


I have a member of class A in my own class which constructor takes multiple parameters. Im forwarding parameters of my own class to the constructor of class A. But its important that these parameters are correct, so i need to check them before consructing the member of A. And heres the problem: I could leave out the member in the member intialization list, effectively calling the default constructor. After the checks in the constructor i could then call A`s constructor in a assigment. Although, this produces a error since the destructor of A is private.

How do i solve this?

MyClass::MyClass(int someParam) : otherMember(2){
//checks for someParam
member = A(someParam); // <- produces error
}

Solution

  • You're going to need an accessible destructor no matter what you do. But to address your question, one option would be to call a static function to check parameters from within the initializer:

    class MyClass {
      private:
        static void checkParam(int);
    // ...
    };
    
    MyClass::MyClass(int someParam) : otherMember( (checkParam(someParam), 2) ) {
      // ...
    }
    
    static void MyClass::checkParam(int someParam) {
      if (...) throw someException();
    }
    

    Note that the , used there is the comma operator, not an argument separator - it evaluates both left and right expressions, and throws away the result of the left.