synaptik
synaptik

Reputation: 9519

C++ dynamically define class member as either an object or a reference to another member

Suppose I have a class as follows:

class Solution {    
public:    
    std::vector<double> x;
}

Suppose I have a function as follows:

void function(Solution& sol) {
    // do some calculations on the solution vector
}

Under some circumstances, I will want function to perform calculations directly using the vector x. However, under some circumstances I will want to perform calculations using another vector that is produced by a mapping of the vector x.

Give these possible circumstances, it makes sense to introduce an additional member to the class Solution, but in the first circumstance this additional member will simply refer to x, and in the second circumstance this additional member will itself be another std::vector that is determined by a mapping of some form.

So, ideally I could add a ctor to Solution that creates/defines a member named y either as a std::vector or as merely a reference to x. Then, my function could simply operate directly using y.

How might I do this?

Upvotes: 1

Views: 277

Answers (1)

Michael Shmalko
Michael Shmalko

Reputation: 710

You can define your function as:

void function(std::vector<double>& x)

And pass different vectors to it, depending on circumstances

Edit Using references in ctors

class Solution 
{    
    std::vector<double> x;
    std::vector<double>& y; 
public:    
    Solution(std::vector<double>& _y) : y(_y) { }
    Solution() : y(x) { }
    void function() { /* do work on y*/ }    
};

This way your function always operates on the same reference, but you can control what data this reference refers to. Note that x and y are now private -- this ensures that these members are only used locally via function() method.

Upvotes: 4

Related Questions