Search code examples
c++oopconstructorconstantsinitializer-list

Initialize multiple constant class members using one function call C++


If I have two different constant members variables, which both need to be initialized based on the same function call, is there a way to do this without calling the function twice?

For example, a fraction class where numerator and denominator are constant.

int gcd(int a, int b); // Greatest Common Divisor
class Fraction {
public:
    // Lets say we want to initialize to a reduced fraction
    Fraction(int a, int b) : numerator(a/gcd(a,b)), denominator(b/gcd(a,b))
    {

    }
private:
    const int numerator, denominator;
};

This results in wasted time, as the GCD function is called twice. You could also define a new class member, gcd_a_b, and first assign the output of gcd to that in the initializer list, but then this would lead to wasted memory.

In general, is there a way to do this without wasted function calls or memory? Can you perhaps create temporary variables in an initializer list?


Solution

  • In general, is there a way to do this without wasted function calls or memory?

    Yes. This can be done with a delegating constructor, introduced in C++11.

    A delegating constructor is a very efficient way to acquire temporary values needed for construction before any member variables are initialized.

    int gcd(int a, int b); // Greatest Common Divisor
    
    class Fraction {
    public:
        // Call gcd ONCE, and forward the result to another constructor.
        Fraction(int a, int b) : Fraction(a,b,gcd(a,b))
        {
        }
    private:
        // This constructor is private, as it is an
        // implementation detail and not part of the public interface.
        Fraction(int a, int b, int g_c_d) : numerator(a/g_c_d), denominator(b/g_c_d)
        {
        }
        const int numerator, denominator;
    };