1

I am write this code but when i compile this code with g++ in arch linux i recive this error

  /tmp/ccG7axw1.o: In function `saving::calculate()':
  saving.cpp:(.text+0x3a): undefined reference to `saving::rate'
  /tmp/ccG7axw1.o: In function `saving::modify()':
  saving.cpp:(.text+0x93): undefined reference to `saving::rate'
  collect2: error: ld returned 1 exit status

saving.h

class saving{
private :
    double savebal;
public :
    saving(double newSavebal); 
    double calculate();
    void modify();
    static double rate;
};

saving.cpp

#include<iostream>
#include"saving.h"
using namespace std;
saving :: saving(double newSavebal){
   savebal = newSavebal;
}
double saving :: calculate(){
    savebal += (savebal * (rate / 100))/12;
}

void saving :: modify(){
    cout<<"Please enter the new rate"<<endl;
    cin>>rate;
}

mainSaving.cpp

#include<iostream>
#include"saving.h"
using namespace std;
void menu(saving );
int main(){
      saving s1(500);
      menu(s1);
}

  void menu(saving s){
    int m;
    cout<<"1) calculate month interest\n";
    cout<<"2) change rate of interest\n";
    cin>>m;
    switch(m){
        case 1 :
         s.calculate();
         break;
        case 2 :
         s.modify();
         break;

    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Amor
  • 43
  • 1
  • 9

2 Answers2

0

In Saving.h, you declared the static variable:

static double rate;

But you still need to define it (in other words instantiate it). To do so you should add this to Saving.cpp:

 double saving::rate = 0;

Without that, the linker cannot find the actual variable, so any reference to it will result in a linker error.

A.S.H
  • 29,101
  • 5
  • 23
  • 50
0

Because saving is a static member, you have to have it initialized beforehand.

In your saving.cpp file, add this line after including all the headers:

double saving::rate = 0

Your code should then like this:
#include<iostream>
#include"saving.h"
using namespace std;

double saving::rate = 0; //With this line here

saving :: saving(double newSavebal){
   savebal = newSavebal;
}
picklechips
  • 746
  • 2
  • 8
  • 28