Aditya Jain
Aditya Jain

Reputation: 59

Pass function parameter directly to class variable

I have a class lazy_segment_tree. This is the current constructor

template<typename T>
struct lazy_segment_tree{
    int n;
    int H;
    T base;
    vector<T> segtree;
    vector<T> lazytree;
    T (*join)(T,T);
    T (*assign)(int,T,T);
    lazy_segment_tree(vector<T> &seq, T (*merge)(T,T), T (*create)(int, T,T), T defvalue){
        join=merge;
        assign=create;
        base=defvalue;
        n=seq.size();
    }
};

Can't I directly make the construction parameters go to the values in the class variable?

Upvotes: 0

Views: 435

Answers (1)

a-doctor
a-doctor

Reputation: 26

I am not 100% sure what do you mean by 'directly'.

But in this case you should use initializer list to initialize the member variables. More on initializer lists here.

Applied to your code, the constructor would now look like this:

lazy_segment_tree(vector<T> &seq, T (*merge)(T,T), T (*create)(int, T,T), T defvalue)
    : join(merge)
    , assign(create)
    , base(defvalue)
    , n(seq.size())
{}

In your original code, all the members are first default-constructed during initialization of the class. Then, the body of the constructor is called where you use '=' to copy assign the constructor parameters.

When initializer list is used, the members are directly constructed with specified parameters.

Depending on what T might be, it may or may not make real difference. Nevertheless, initializer lists are the standard way to initialize class members and you should use it if possible.

Upvotes: 1

Related Questions