Declaring Variable Inside Member Function

Sep 15, 2011 at 7:41pm
Hate to ask this, because I've worked around it in the past, but I can't recall how to fix this issue.

So I have an assignment in a class, I can only have one public data member, that of which I already have "r" for the ratio in a geometric series.

One of my member functions needs to calculate the series partial sum (taking in a variable "n") for the number of summations, easy enough, could do this in 30 seconds with an additional data member. But I can't have that data member. I also can't pass in "sum" as an argument to the member function.

Also, apparently one cannot use local variables inside member functions (ie declaring it inside the member function such as "double sum" will not work). Does using a temp get around this? I need to return the partial sum, but I have no idea how to get a temporary variable inside my member function to hold the data until the loop is complete, and then pass it to return. Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include"GeometricSeries.h"
#include<limits>
#include<cmath>

GeometricSeries::GeometricSeries(const double r) :
r(r) {}

  double GeometricSeries::partial_sum(int n){

	  double sum; //Can't do this obviously, but helps with illustration

	  for(int i = 0; i < n; i++){

		  sum = sum + pow(r, i);

	  }

	  return sum;
  }

  double GeometricSeries::limit() const{

	  if (abs(r) < 1) return 1/(1-r);

	  if (r < -1) return std::numeric_limits<double>::quiet_NaN();

	  if (r >= 1) return std::numeric_limits<double>::infinity();

  }
Sep 15, 2011 at 7:43pm
Of course you can declare local variables in methods. Where did you get this ridiculous idea from?
Last edited on Sep 15, 2011 at 7:43pm
Sep 15, 2011 at 8:13pm
When I try, I get this:

Warning: uninitialized local variable used 'sum'

Then when I run I get:

Run-Time Check Failure #3 - The variable 'sum' is being used without being initialized.

This is ran just as it appears above.
Sep 15, 2011 at 8:16pm
AHHH stupid move, initialize. Had to set it = 0. Thanks, I think I just needed a kick to the brain.
Sep 15, 2011 at 11:56pm
If you declare a local variable that is not an integral type (ie some object of a class), and that class has a default constructor, then the default constructor will be called and you don't have to initialise it. For example strings.

std::string blah;

will initialise to an empty string.

However, if you are declaring a local variable that is an integral type (eg int, double), then it will initialise to 0 if it is declared in global scope, otherwise it will remain uninitialised.

The easy way to not have to remember any of this is to always initialise.
Topic archived. No new replies allowed.