Hi iam begginer at c++ i have class with static methods and i cant access them it throws me an error
1>------ Build started: Project: CPractice, Confi
You only declared name
in the class, static variables need to be defined like so outside of the class:
string CPractice::name ="hello" ;
static string name;
As it is static
, this line only declares name
- you need to define it too. Simply place this below your class definition:
string CPractice::name;
If you end up moving your class to a corresponding header and implementation file, make sure you place this definition in the implementation file. It should only be defined in a single translation unit.
Since name is a static data member you should initialize it :) and not count on the default instance related constructor.
Add this after the class definitions (yep, I know its confusing since your member is a private one, but this is only an initialization) :
string CPractice::name;
I think you're trying to compile with gcc
, when you should be compiling with g++
. See What is the difference between g++ and gcc? for more on this.
You also need to add string CPractice::name;
below your class definition.