cesar
cesar

Reputation: 9064

I'm trying to declare a constant string in my C++ class, but I get an "Invalid in-class assignment", and I don't understand why

here's the code:

#include <string>

class Config {
public:
    static const std::string asdf = "hello world!";
}

I can't diagnose why this won't work

Upvotes: 2

Views: 449

Answers (5)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361254

Only integral types can be initialized in the class (presuming they're declared as static const).

So do this:

//Config.h
class Config 
{
public:
    static const std::string asdf; //declaration
    static const int demo_integral = 100; //initialization is allowed!
}

//Config.cpp 
const std::string Config::asdf = "hello world!"; //definition & initialization 
const int Config::demo_integral; //already initialized in the class!

Definitions should be in .cpp file, or else you will get multiple definition error if you define them in the header file itself and then you include the header file in multiple files!

Upvotes: 3

Steve Walsh
Steve Walsh

Reputation: 6645

From:

http://cplusplus.syntaxerrors.info/index.php?title=Invalid_in-class_initialization_of_static_data_member_of_non-integral_type_%E2%80%98const_char*%E2%80%99

You are only allowed to first assign variables that are enumeration types or"integral" types -- int, char, long, etc -- inside a class definition. Char* is not an integral type, so you can only assign to it in global scope.

It is possible for you to do this as a workaround:

#include <string>

class Config {
public:
    static const std::string asdf()
    {
       return "Hello World!";
    }
};

Upvotes: 2

Adrian
Adrian

Reputation: 20058

You have to declare it outside of the class:

#include <string>

class Config {
public:
    static const std::string asdf = "hello world!";
}

const std::string Config::asdf = "hello world";

Also look here.

Upvotes: 2

Didier Trosset
Didier Trosset

Reputation: 37427

Apart from integral types, static const members cannot be initialized within the class definition scope. You have to split it, as follows.

In header file:

#include <string>

class Config {
public:
    static const std::string asdf;
};

And in .cpp file

const std::string Config::asdf = "hello world!";

Upvotes: 3

Kiril Kirov
Kiril Kirov

Reputation: 38143

You cannot do this.

As it is static, it must be defined outside the class ( const std::string asdf inside your class is only declaration, because of the static)

In your case:

const std::string Config::asdf = "hello world!"

You should initialize all data members inside constructor, not like this:

class A
{
    var_t var = value;
};

Upvotes: 3

Related Questions