Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8166389
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T19:50:54+00:00 2026-06-06T19:50:54+00:00

I want to throw an exception in my constructor so that I don’t have

  • 0

I want to throw an exception in my constructor so that I don’t have to deal with zombie objects. However I also want to provide a validation method upfront so that people can avoid “dealing with exceptions” where there is no cause to. In a GUI it’s not exceptional to expect invalid data. However I also want to avoid code duplication and overhead. Is GCC / Microsoft Visual C++ compiler smart enough to remove this inefficiency of validating an input twice and if not, is there a subtle change that could please?

An example code block illustrating my point is below:

#include <string>
#include <exception>
#include <iostream>

using std::string;
using std::cout;
using std::endl;
using std::exception;


// a validation function
bool InputIsValid(const string& input) {
    return (input == "hello");
}

// a class that uses the validation code in a constructor
class MyObject {
    public:

    MyObject(string input) {
        if (!InputIsValid(input))    //since all instances of input
            throw exception();       //has already been validated
                                     //does this code incur an overhead
                                     //or get optimised out?

        cout << input << endl;       
    };

};

int main() {

    const string valid = "hello";

    if (InputIsValid(valid)) {
        MyObject obj_one(valid);
        MyObject obj_two(valid);
    }

    return 0;
}

I anticipate this may not be possibly if the object file for the class is generated alone as the object file has no way to ensure people will validate before calling the constructor, but when an application is compiled and linked together in a single application, is it possible please?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T19:50:55+00:00Added an answer on June 6, 2026 at 7:50 pm

    Is there an overhead of validating in a constructor if all data may already be valid?

    Yes, if the data is already validated, then you would incur the cost of validating it again

    Is GCC / Microsoft Visual C++ compiler smart enough to remove this inefficiency of validating an input twice and if not, is there a subtle change that could please?

    You could encapsulate your input in an object, and that object would remember the result of validation.

    template <typename INPUT_TYPE>
    class InputObject {
        INPUT_TYPE input_;
        bool valid_;
    public:
        typedef <typename VALIDATE>
        InputObject (INPUT_TYPE in, VALIDATE v) : input(in), valid_(v(in)) {}
        const INPUT_TYPE & input () const { return input_; }
        bool isValid () const { return valid_; }
    };
    
    typedef InputObject<std::string> MyInput;
    
    class MyObject {
    public:
        MyObject (const MyInput &input) {
            if (!input.isValid()) throw exception();
            //...
        }
    };
    

    The constructor to InputObject calls the validator function for you, and stores the result of validation in a flag. Then MyObject just checks the flag, and doesn’t have to do the validation again.

    int main () {
        MyInput input("hello", InputIsValid);
    
        try {
            MyObject obj_one(input);
            MyObject obj_two(input);
        }
        catch (...) {
            //...
        }
    }
    

    As suggested by DeadMG, stronger type checking can be achieved by insisting that MyObject only accept validated input. Then, it would not need to throw in the constructor at all. Such a scheme could be accomplished by making NonValidatedInput and ValidatedInput two different types.

    template <typename> class NonValidatedInput;
    
    template <typename T>
    class ValidatedInput {
        friend class NonValidatedInput<T>;
        T input;
        ValidatedInput (const T &in) : input(in) {}
    public:
        operator const T & () const { return input; };
    };
    
    template <typename T>
    class NonValidatedInput {
        T input;
    public:
        operator ValidatedInput<T> () const { return ValidatedInput<T>(input); }
        template <typename V>
        NonValidatedInput (const T &in, V v) : input(in) {
            if (v(input) == false) throw exception();
        }
    };
    

    NonValidatedInput accepts non-validated input, and performs the validation, and can be converted to a ValidatedInput object if the validation succeeds. If the validation fails, NonValidatedInput throws an exception. Thus, MyObject has no need to check for validation at all, because it’s constructor only accepts ValidatedInput.

    typedef ValidatedInput<std::string> MyInput;
    
    class MyObject {
    public:
        MyObject (MyInput input) {
            std::string v = input;
            std::cout << v << std::endl;
        }
    };
    
    int main () {
        try {
            MyInput input = NonValidatedInput<std::string>("hello", InputIsValid);
            MyObject obj_one(input);
            MyObject obj_two(input);
        }
        catch (...) {
            //...
        }
    }
    

    The type safety here is quite strong, because only NonValidatedInput can create a ValidatedInput, and only if the validation succeeded.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to throw an exception to say that we have an invalid email
I want to call a function that may throw an exception. If it does
i have about 20 possible exception messages that i want thrown when an error
I have a list of 10 data objects that I want to insert/update to
std::exception requires that its constructor be throw() . Yet std::runtime_error accepts a std::string as
Suppose you want to throw Exception like this: 'Project with the provided ID cannot
I want to throw an exception if cardescription is in table in row with
Suppose I want to throw a new exception when invoking a generic method with
I want to throw my own exceptions with the base class Exception . There
HttpResponse.End() seems to throw an exception according to msdn. Right now i have the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.