C++ – Unresolved External Symbol Error in C++

c++

I am trying to do a simple hw problem involving namespace, static data members and functions. I am getting an unresolved external symbol error

Error   1   error LNK2001: unresolved external symbol "private: static double JWong::SavingsAccount::annualInterestRate" (?annualInterestRate@SavingsAccount@JWong@@0NA)    SavingsAccount.obj  SavingsAccount

And I don't see why I am getting this error. Maybe I don't know something about static variables compared to regular data members that is causing this error. Here is my code:

SavingsAccount.h file

#ifndef JWONG_SAVINGSACCOUNT_H
#define JWONG_SAVINGSACCOUNT_H

namespace JWong
{
    class SavingsAccount
    {
    public: 
        // default constructor
        SavingsAccount();
        // constructor
        SavingsAccount(double savingsBalance);

        double getSavingsBalance();
        void setSavingsBalance(double savingsBalance);
        double calculateMonthlyInterest();

        // static functions
        static void modifyInterestRate(double newInterestRate);
        static double getAnnualInterestRest();
    private:
        double savingsBalance;

        // static members
        static double annualInterestRate; 
    };
}

#endif

SavingsAccount.cpp file

#include <iostream>
#include "SavingsAccount.h"

// default constructor, set savingsBalance to 0
JWong::SavingsAccount::SavingsAccount() : savingsBalance(0)
{}

// constructor
JWong::SavingsAccount::SavingsAccount(double savingsBalance) : savingsBalance(savingsBalance)
{}

double JWong::SavingsAccount::getSavingsBalance()
{
    return savingsBalance;
}

void JWong::SavingsAccount::setSavingsBalance(double savingsBalance)
{
    this->savingsBalance = savingsBalance;
}

// returns monthly interest and sets savingsBalance to new amount
double JWong::SavingsAccount::calculateMonthlyInterest()
{
    double monthlyInterest = savingsBalance * SavingsAccount::annualInterestRate / 12; 
    setSavingsBalance(savingsBalance + monthlyInterest);
    return monthlyInterest; 
}

void JWong::SavingsAccount::modifyInterestRate(double newInterestRate)
{
    SavingsAccount::annualInterestRate = newInterestRate;
}

double JWong::SavingsAccount::getAnnualInterestRest()
{
    return SavingsAccount::annualInterestRate;
}

Best Answer

I'm presuming you are actually compiling the .cpp file (because the other functions link).

The error is likely due to not defining the annualInterestRate static variable.

You have declared it (in the class header), but it's not defined. In your cpp file add:

// static member definition
double JWang::SavingsAccount::annualInterestRate = ...;

See an article highlighting the difference between declaration and definition of static members.

Section 9.4.2 of the C++ Standard says "The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition."

Related Question