2

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";

    }
0

1 Answer 1

1

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()
{
}
Sign up to request clarification or add additional context in comments.

9 Comments

Do i Need to manually Call InitInfo() for initializing the variables. Or only I need to call is the variable TestClassObject?
@HariSankarvm If you provide a constructor to your class instead of your initInfo function, you could just create the object directly: TestClass TestA::testClassObject("name", "class", "description");
@HariSankarvm You want to initialize the object by the function. So you should provide a function call to initialize the object.
@HariSankarvm You could alternatively leave the return type as void and call TestA::initInfo() from within main. That's especially interesting if you want to call it multiple times, as you don't need the assignment any more (but it would then probably better be called reset...).
@HariSankarvm Without the function you can just write TestClass TestA::TestClassObject = { "Name", "ClassName", "Description of class" };
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.