overloading operator- power operator

i created a fraction class and now im trying to create an overload operator for the power function to take a fraction to the "n" power, but Im getting an identifier undefined error for *tmp. Any help on this problem would be greatly appreciated. I have posted the overload code from the h file and the code from the exp function from the cpp file.

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
Fraction & operator ^(int n){
		int sign = 1;
		if(n < 0){
			sign = -1;
			n = -n;
		}
		int numer = exp(*num, n);
		int denon= exp(*den, n);
	

		if (sign > 0)
			Fraction *tmp = new Fraction(numer, denon);
		
		else //if (*num != 0).... else ......
			Fraction *tmp = new Fraction(denon, numer);
		return *tmp;



//this is code from cpp file
int exp(int b, int ex){
	if(ex == 0 || b==1)
		return 1;
	if(b == 0)
		return 0;
	if (ex < 0)
		return 1/(b*exp(b, ex-1));
	else
		return b*exp(b, ex-1);
}
I will explain what has happened here..
1
2
3
4
5
6
7
8
if (sign > 0)
Fraction *tmp = new Fraction(numer, denon); // declare tmp  
		// tmp is  out of scope (one line scope )
		else //if (*num != 0).... else ......
			Fraction *tmp = new Fraction(denon, numer); // same here as above

		return *tmp; //undefined



to be more clear..
I will also give this example

1
2
3
4
5
6
7
8
9
if (something)
    int x  = 6 ;
else
    int x = 17 ;

// x is out of scope
 cout << x ;  //undefined 



The right way to do this
1
2
3
4
5
6
7
8
int x ;

if (something)
     x = 6; 
else
     x = 17 ;

cout << x ; //Ok   


Also you have caused memory leak when the pointer (tmp)
out of scope and not freed .. so be careful


Last edited on
@obscure, ahhh thank you. much clearer now
Topic archived. No new replies allowed.