Data change varification

Hi,

I have created a class that gets some data as an input and uses this to do some calculations. Since the data should not be changed within the class it is provided as a constant reference (const InputData& data).

My problem however is that data is now only available for the constructor. I would however like to have it available for all private functions called by the constructor as well without having to pass it along. I have thought of two possibilities to do this but do not know how to implement them.

The first would be to create a global (to the class) variable InputData data_ and then simply do the following.

1
2
3
4
5
SampleClass::SampleClass(cont InputData& data){
data_ = data;
/* the rest of the code */
if (data != data_) error("Somethin went wrong");
}


The problem here is that I have not defined the operator != and don't know how.

The second, in my opinion, better solution would be to define const InputData data_ rather then just InputData data_ but how would I then be able to get data_ to equal data?

Thanks for your help!
Ben
Have a non-static member variable of type const InputData in the class. And initialize it in the constructor:

struct InputData { /* ... */ } ;

1
2
3
4
5
6
struct SampleClass 
{
    SampleClass( const InputData& data ) : data_( data ) {}
    // ...
    const InputData data_ ;
};
Data should be available to all the other classes... what you said doesn't add up.

If you want to have data available even outside the class as a unique variable for your whole program, you can define it as static.

1
2
3
4
5
6
7
class MyClass
{
public:
    static vector<double> myData;
};

vector<double> MyClass::myData; //initialize 


After that your thingy will be accessible from your whole program through:

 
MyClass::myData
@JLBorges
I will try out your comment. Thanks for now.

@TheDestroyer
My meaning was a bit different. The problem is something like this:
1
2
3
4
5
6
int main(){
//... some code
InputClass inputData();
//... geting data
Calculation calculation(data);
}

in a different included file
1
2
3
4
5
6
7
8
struct InputData{
 float a
 flaot b
}

class InputClass{
// some means to get the input data from file and make it available in main (though not through a public static! - That might however be a good idea)
}


1
2
3
4
class Calculation(const InputData& data){
// some stuff
step(); // calling a member function - here data is not defined - but needs to be.
}


I hope this makes my meaning clearer. Sorry that it is a bit messy.
Last edited on
@JLBorges
That does excellently what I was looking for. Great help!

Tak! (Danish for Thanks)
Topic archived. No new replies allowed.