Home > other >  How can a static void class function be initialized in the header of a C program?
How can a static void class function be initialized in the header of a C program?

Time:07-02

I am supposed to initialize a static string, which is a private member of the class, with a setter which is a public member of the same class, from outside of the class, and in the same namespace.

Here is the code template I was given. Changing the College class is not allowed.

#include <iostream>

using namespace std;

class College
{
private:
    static string principal_name; // principal_name is common for all the students

public:
    static void setPrincipalName(string name)
    {
        principal_name = name;
    }

    static string getPrincipalName()
    {
        return principal_name;
    }
};

//Initialize the static principal_name variable with value "John" here

string College::setPrincipalName("John");

CodePudding user response:

string College::setPrincipalName("John"); is not legal or correct. You need to define the actual College::principal_name variable instead, eg:

string College::principal_name = "John";

Even then, don't define it in the header file itself. Every file that includes the header will try to re-define the variable, leading to linker errors. Define the variable one time in a separate .cpp file instead, eg:

College.h

#ifndef CollegeH
#define CollegeH

#include <iostream>

using namespace std;

class College
{
private:
    static string principal_name; // principal_name is common for all the students

public:
    static void setPrincipalName(string name)
    {
        principal_name = name;
    }

    static string getPrincipalName()
    {
        return principal_name;
    }
};

#endif

College.cpp

#include "College.h"

string College::principal_name = "John";

After that, you can use College::setPrincipalName() and College::getPrincipalName() anywhere else, as needed.

CodePudding user response:

with c 17, simply use static inline

class College
{
    static inline std::string principal_name = "John";
};
  •  Tags:  
  • c
  • Related