I am new to c++ and exploring the static feature on class members and functions.
person.h
#include <iostream>
using namespace std;
namespace school
{
class Person
{
public:
static const int MAX=99;
private:
static int idcount;
public:
static void setID(int id) { idcount = id;}
static int getID() { return idcount;}
private:
string name;
public:
Person();
Person(const Person &other);
~Person();
};
}
Person.cpp
#include "person.h"
namespace school
{
//Constructor
Person::Person()
{
this->name = "";
cout << "object created" << endl;
}
//Copy Constructor
Person::Person(const Person &other)
{
this->name = other.name;
}
//Destructor
Person::~Person()
{
cout << "Destructor Called" << endl;
}
}
main.cpp
#include "person.h"
int main()
{
cout << school::Person::MAX << endl;
school::Person::setID(5);
cout << school::Person::getID() << endl;
return 0;
}
i am getting the below linker error when i compile the above code. but when i change the idcount to public and declare it main ( int Person::idcount;) then i have no issues.
D:\Hari\Project\CPP_Practise\build>mingw32-make
[ 50%] Built target person
Scanning dependencies of target app
[ 75%] Building CXX object CMakeFiles/app.dir/chapter2/classes2.cpp.obj
[100%] Linking CXX executable app.exe
CMakeFiles\app.dir/objects.a(classes2.cpp.obj): In function
`ZN6school6Person5se
tIDEi':
D:/Hari/Project/CPP_Practise/chapter2/person.h:21: undefined reference to
`schoo
l::Person::idcount'
CMakeFiles\app.dir/objects.a(classes2.cpp.obj): In function
`ZN6school6Person5ge
tIDEv':
D:/Hari/Project/CPP_Practise/chapter2/person.h:22: undefined reference to
`schoo
l::Person::idcount'
collect2.exe: error: ld returned 1 exit status
CMakeFiles\app.dir\build.make:97: recipe for target 'app.exe' failed
mingw32-make[2]: *** [app.exe] Error 1
CMakeFiles\Makefile2:103: recipe for target 'CMakeFiles/app.dir/all'
failed
mingw32-make[1]: *** [CMakeFiles/app.dir/all] Error 2
Makefile:82: recipe for target 'all' failed
mingw32-make: *** [all] Error 2
What should i do when i am using it as private static variable?