Thread: Static data member already defined

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    48

    Static data member already defined

    Code:
    // MAIN.cpp
    #include <iostream>
    #include "Person.h"
    using namespace std;
    
    
    int main()
    {
    
            return 0; 
    }
    Code:
    // Person.h
    #ifndef PERSON_H
    #define PERSON_H
    
    class Person
    {
    public:
    
        static int testme;
    
    };
    
    int Person::testme = 10;
    #endif
    Code:
    //Person.cpp
    #include "Person.h"
    It shows me linker error. static int testme already defined.
    I want to use testme in both person.cpp and main.cpp.. Now what should I do?

  2. #2
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    Static member variables must be defined in the .cpp, not in the header. The declaration must remain in the header, but the initialization must be moved to the .cpp.

    EXCEPTION: If your static member is of an integral type (i.e. char, int, etc.) and const, you can just initialize in the header.

    example:

    Code:
    #ifndef PERSON_H
    #define PERSON_H
    
    class Person
    {
    public:
    
        static const int testme = 10;
    
    };
    
    #endif

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    48
    But how can I use testme variable in both person.cpp and main.cpp ?

  4. #4
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    Quote Originally Posted by freiza View Post
    But how can I use testme variable in both person.cpp and main.cpp ?
    Like I said, just move the int Person::testme = 10; part to person.cpp and leave the rest in person.h. Just try it, it'll work.

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    48
    Yes, It did. Now I understand what you were trying to say. Thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. static pointer data member
    By suppu143 in forum C++ Programming
    Replies: 2
    Last Post: 03-14-2011, 07:46 AM
  2. Static Data Member
    By vb.bajpai in forum C++ Programming
    Replies: 3
    Last Post: 06-21-2007, 11:29 AM
  3. Static & Data Member
    By ecoliteracy in forum C++ Programming
    Replies: 1
    Last Post: 04-16-2007, 08:46 PM
  4. Can not access static data member.
    By CottonXu in forum C++ Programming
    Replies: 5
    Last Post: 11-04-2005, 11:41 AM
  5. Static member data inaccessible
    By BSTRhino in forum C++ Programming
    Replies: 2
    Last Post: 01-10-2002, 09:28 PM