Accessing class variables from .hpp file in the .cpp file

AI Thread Summary
The discussion revolves around accessing class variables in C++ and the unexpected behavior when using a class member variable versus a hardcoded value. The user reports that while both approaches yield the same output from the function, the integral function returns zero when using the class member variable. It is suggested that the issue arises from not properly initializing the pointer to the class instance in the struct used for integration. The solution involves ensuring that the `cfunc` field in the struct is set to point to the correct class instance before calling the integral function. Debugging techniques, such as using breakpoints, are recommended to trace variable values and identify the source of the issue.
CAF123
Gold Member
Messages
2,918
Reaction score
87
Hi all, simple question but I cannot understand what is going wrong. I have a CLASS.hpp file of the form
Code:
class CLASS
{
   private:
      double varA = 5.; //some numerical value

   public:
      double func(double z);
 };

and then in the CLASS.cpp file I have a call to this function func() via:
Code:
#include "CLASS.hpp"
double CLASS::func(double z) {
     double var = varA; //or this->varA should work too
     double result = var*var; //some function of var
     return result;      
};

The code compiles and runs fine, the problem is when I replace varA with 5. in the double func, the output is different than if I do as above. Of course my code is more complicated but I have checked that when I replace varA with 5 rather than fetching the value from the header file, the output changes. Is there something wrong in the above? Thanks!
 
Last edited by a moderator:
Technology news on Phys.org
First off, please use code tags! I have edited your post to include them.

Regarding your code, I'm not seeing what the problem is. I ran your code both ways -- with the private member varA initialized to 5.0, and with the local variable var initialized to 5.0. Both ways produced 25.0 as the return value.
Here's my code:
The header file (which I call Header.h):
Code:
class CLASS
{
  private:
    double varA = 5.; //some numerical value

  public:
    double func(double z);
};

Source.cpp
C++:
#include "Header.h"

double CLASS::func(double z)
{
    double var = 5.0; // varA; //I can hardcode var to 5.0 or init it with varA -- no difference
    double result = var * var; //some function of var
    return result;
};

int main()
{
    CLASS cl;
    double answer = cl.func(2.0);
}
You didn't include the "driver" code, so perhaps you aren't creating an instance of your class? In my code the value returned to answer either way is 25.0.

Alternatively, the func function definition can be placed in the header file, with again no difference in outcome.

BTW, I'm using Visual Studio 2017.
 
Last edited:
  • Like
Likes sysprog and pbuk
Thanks, yes I have tried printing out the value of the function using both ways and they both return the same answer like you have. So, the problem must be elsewhere. I am also calling the `func´(which in my actual code represents an integrand) in another function (which does an integration) and so somehow when I fetch the value from the header it is not being passed through properly (which is strange because the the value of the function is the same both ways, I checked this in the same way you did with calling non-static function using the instance in main). Since the code still compiles and runs, it seems there is not an error but that cpp assigns a random value to this parameter or something. Strange. Since I cannot upload all my code here probably I'll think about it a bit longer.
 
CAF123 said:
So, the problem must be elsewhere. I am also calling the `func´(which in my actual code represents an integrand) in another function (which does an integration) and so somehow when I fetch the value from the header it is not being passed through properly (which is strange because the the value of the function is the same both ways, I checked this in the same way you did with calling non-static function using the instance in main). Since the code still compiles and runs, it seems there is not an error but that cpp assigns a random value to this parameter or something. Strange.
The debugger is your friend... Put breakpoints at suitable places in your code, run until you hit a breakpoint, then step through your code looking at the values of relevant variables.
 
  • Like
Likes sysprog
Mentor note: This post and the following three posts were moved from another thread into this one.

Hi all, I am trying to fetch a value from CLASS.hpp to be passed to an integrand function and then to the integral function, see below for my code spread across CLASS.hpp (header file), CLASS.cpp (source file) and main.cpp (main function along with integrand and integral function).
The problem I am having is when the variable double var in the .cpp is set equal to varA, then the integral returns zero, otherwise if I hardcode double var to the value in the .hpp file, it returns the correct answer. In BOTH cases, the value of func is 25., as I also checked.

In one case, I get output

25
0

and in the other,

25
124740

The latter is the correct one but I would like to understand what I am doing wrong with trying to fetch the value from the header file for the value for var in func in the CLASS.cpp file. Thanks very much!

CLASS.hpp;
Code:
class CLASS
{
    private:
       double varA = 5.; //some numerical value

    public: double func(double z);
};

CLASS.cpp:
Code:
#include "CLASS.hpp"
#include <iostream>

double CLASS::func(double z) {

    double var = varA; // if hardcode `double var = 5.;`then code works (where 5. is the value of varA in .hpp). As it stands with `double var = varA;' the integral returns zero.
    double result = var * var;
    return result;
};

main.cpp:
Code:
#include "CLASS.hpp"
#include <iostream>
#include <gsl/gsl_integration.h> // GNU Scientific Library integration routines
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_min.h>

struct struct1_t // structure for storing integrand parameters
{
  CLASS *cfunc;
};

double integrand(double z, void *p)
{
    double coeff;
    double res;
    double N = 1.;
    double a = 2.;
    double b = 3.;

    struct1_t &struct1 = *(struct1_t *)(p);
   
    coeff = struct1.cfunc->func(z);
  
    double f = N*pow(z,a)*pow(1-z,b);

    return res = coeff*f;

}

double convolute(double lb, double ub, double epsabs, double epsrel, struct1_t struct1, double func1(double, void *))
{
    double result;
    double err;
    double res;
   
    gsl_integration_workspace * Workspace = gsl_integration_workspace_alloc (3e8);
    gsl_function F;
    F.params = (void*)(&struct1);
    F.function = func1;
    gsl_integration_qags(&F, lb, ub,
                         epsabs, epsrel, 3e8,
                         Workspace, &result, &err);
   
    gsl_integration_workspace_free(Workspace);
   
    return res = result;
}

double integral(struct1_t structintegrand) {

    double epsabs = 1e-3;
    double epsrel = 1e-3;
    double lb  = -5.;
           
       double  convolutionRes =
            convolute(lb,0.0,epsabs,epsrel,structintegrand,&integrand);
   
    return  convolutionRes;
}

int main() {

  struct1_t struct1;
  CLASS *cfunc;

  CLASS cl;
  double answer = cl.func(2.0);
  std::cout << answer << std::endl;
  std::cout << integral(struct1) << std::endl;
};
 
Last edited by a moderator:
Mark44 said:
The debugger is your friend... Put breakpoints at suitable places in your code, run until you hit a breakpoint, then step through your code looking at the values of relevant variables.
Thanks, I have used the lddb debugger but can't quite understand why the value is being set to zero when I pass it to my integral function. I have made another thread in the same forum where I have reproduced the problem with minimal code. Thanks a lot.
 
You call intergral(struct1) with a default constructed struct1_t, i.e. you do not seem to set its cfunc field anywhere so that it points to you cl variable.
 
Filip Larsen said:
You call intergral(struct1) with a default constructed struct1_t, i.e. you do not seem to set its cfunc field anywhere so that it points to you cl variable.
I see, thanks, I thought I had done that with the CLASS *cfunc in the definition of the struct1_t at the beginning of main.cpp. Is there something else I need to add elsewhere in the main.cpp integrand or integral functions? I had tried structintegrand.cfunc->varA; in the integral function but it seems this is not correct.
 
If you are able to collect all your needed parameters and method in a single class (e.g. CLASS), then you can just pass a pointer in for that when you call the library functions instead of using struct1_t. This means whenever you have a "void *p" parameter passed in you can cast that using "CLASS& cp = *(CLASS*)p;".

On the other hand, if you want to keep using struct1_t as your code was setup to then you probably just need to add "struct1.cfunc = &cl;" somewhere after you declare struct1 and cl but before using struct1.

If all this makes little sense to you, I guess I don't need to point out that you probably will benefit from reading up on C++ in general, and pointers in particular :wink:
 
  • Like
Likes pbuk
Back
Top