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

In summary, you are trying to call a function in a source file with a value that has been hardcoded in the header file. Both cases result in the function returning the wrong value.
  • #1
CAF123
Gold Member
2,948
88
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
  • #2
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
  • #3
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.
 
  • #4
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
  • #5
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:
  • #6
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.
 
  • #7
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.
 
  • #8
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.
 
  • #9
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

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

What does it mean to access class variables from a .hpp file in a .cpp file?

Accessing class variables means being able to use and manipulate the variables that belong to a specific class. .hpp files contain class declarations, while .cpp files contain the actual implementation of the class. Therefore, accessing class variables from a .hpp file in a .cpp file allows us to use and modify the variables declared in the class in the actual code.

Why do we need to access class variables from a .hpp file in a .cpp file?

We need to access class variables from a .hpp file in a .cpp file because class variables are private by default, meaning they can only be accessed and modified by functions within the class. By accessing them from the .cpp file, we can use these variables in other parts of our code, making it easier to work with the class.

How do we access class variables from a .hpp file in a .cpp file?

In order to access class variables from a .hpp file in a .cpp file, we need to use the scope resolution operator (::) to specify which class the variable belongs to. This allows us to use the variable outside of the class and manipulate its value.

Can we access private class variables from a .hpp file in a .cpp file?

Yes, we can access private class variables from a .hpp file in a .cpp file by using getter and setter functions. These functions allow us to retrieve and modify the value of private variables, while still keeping them inaccessible to the rest of the code.

What are the benefits of accessing class variables from a .hpp file in a .cpp file?

By accessing class variables from a .hpp file in a .cpp file, we can keep our code organized and modular. It also allows us to use class variables in different parts of our code, making it more versatile. Additionally, it helps to maintain encapsulation, as private variables can only be accessed and modified through designated functions.

Similar threads

  • Programming and Computer Science
Replies
1
Views
992
  • Programming and Computer Science
Replies
6
Views
1K
  • Programming and Computer Science
Replies
6
Views
9K
  • Programming and Computer Science
Replies
2
Views
736
  • Programming and Computer Science
2
Replies
36
Views
4K
  • Programming and Computer Science
Replies
11
Views
1K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
11
Views
2K
  • Programming and Computer Science
Replies
13
Views
2K
Back
Top