Reputation: 1
I have a problem with using return value from other function. Here are some details:
Class1.cpp :
Double Class1::SetValue (double value2)
{
// method code
Return value_set;
}
Class2.cpp:
Void Class2::CountValue(double a)
{
Class1 *object1;
Double value_received= object1->SetValue(object1->value2)
// do something with value_received
}
The problem is that I need to use value_set from SetValue in CountValue in Class2. The code above is giving me error:
Unhandled exception at 0x6462696c in xxx.exe: 0xC0000005: Access violation.
Can you help me, please?
Upvotes: 0
Views: 278
Reputation: 147
There are a couple of issues. There should be no issues with initializing a variable with the return value to some function. We do this all the time, even when you don't normally see the typical function calls like the arithmetic operators or bitwise operators.
With your function
double Class1::SetValue(double value2)
{
//generally you are setting some variable that is a part of Class1
this->value = value2;
//if you are returning something you might want to have some error code
//just in case something went wrong, but it looks like you are just
//returning the number that you are sending in as a parameter.
return value2;
}
I'm not sure what is going on in your next function but we can dissect it.
void Class2::CountValue(double a)
{
Class1 *object1;//this is a pointer to an object, not an instance of an object
// object1 is not initialized so you cannot
// use object1->value2 even if it is set in
// your default constructor
double value_received = object1->SetValue(object1->value2);
// do something with value_received
}
In order for your code to work you might want to alter it to
void Class2::CountValue(double a)
{
Class1 object1;//not a pointer to Class1 anymore
// This will work if object1.value2 is set in the default constructor
double value_received = object1.SetValue(object1.value2);
// do something with value_received
}
or if you are trying to set both value_recieved and object1.value2 we could do
void Class2::CountValue(double a)
{
Class1 object1;//not a pointer to Class1 anymore
double value_received = object1.SetValue(12.2);
// do something with value_received
}
Upvotes: 0
Reputation: 308520
In your SetValue
call, you're passing a parameter of object1->value2
. But you haven't set the pointer object1
yet, it's still uninitialized. That's undefined behavior. You're lucky it crashed or you might have had a much harder time finding it.
Upvotes: 3