Hari Sankar v m
Hari Sankar v m

Reputation: 193

How to Initialize a static class object from a static class function

Initializing the static member TestClassObject showing an error LNK2001: unresolved external symbol.

    class TestClass
            {
            public:
                string sClassName;
                string sName;
                string sDescription;


            };

    class TestA
            {

            private:
                static void InitInfo();  
                static TestClass TestClassObject;
            };

    void TestA::InitInfo()
    {
        TestClassObject.sName = "Name";
        TestClassObject.sClassName = "ClassName";
        TestClassObject.sDescription = "Description of class";

    }

Upvotes: 2

Views: 57

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

You have to define the static data member outside the class definition. Within the class definition it is only declared but not defined.

For example

#include <iostream>
#include <string>

using namespace std;

class TestClass
        {
        public:
            string sClassName;
            string sName;
            string sDescription;


        };

class TestA
        {

        private:
            static TestClass InitInfo();  
            static TestClass TestClassObject;
        };

TestClass TestA::InitInfo()
{
    return { "Name", "ClassName", "Description of class" };
}    

TestClass TestA::TestClassObject = InitInfo();

int main()
{
}

Upvotes: 1

Related Questions