2

I get the error error: ‘Name’ was not declared in this scope What am I missing here.

Source File:

#include<iostream>
#include "scr.h"
using namespace std;

const char* const Test::Name;  

void Test::Print()
{
    cout<<Name;
}

int main()
{       
    Test *t = new Test();
    t->Print();
    delete t;   
}

Header File:

class Test
{   
    static const char* const Name = "Product Name";
    public:
        void Print();
};

EDIT:

If I replace char* const with int, it works. Why?

static const int Name = 4; //in header

const int Test::Name;  //In source

The purpose of the code is to have an alternate for #define as mentioned in Effective C++. In the example there, static const int is used.

4 Answers 4

3

You cannot initialize a static member variable within a class. Not even in the header file.

Header File:

class Test
{   
    static const char* const Name;
    public:
        void Print();
};

In your cpp file:

const char* const Test::Name = "Product Name";

Edit: I must have added that the initialization is allowed only for int and enumerations and that too with constants that can be evaluated at compile time.

Sign up to request clarification or add additional context in comments.

Comments

2

You can't initialize members in class definition.

Take a look at Parashift post - Can I add = initializer; to the declaration of a class-scope static const data member?

SUMMARY: The caveats are that you may do this only with integral or enumeration types, and that the initializer expression must be an expression that can be evaluated at compile-time: it must only contain other constants, possibly combined with built-in operators.

2 Comments

@cod3r - Read the link I've posted.
@cod3r -Thanks! Glad you got it useful. I'm a big admirer of ParaShift.
1

In general, you can't initialize static variables directly in the class definition, you have to do it in a separate source file, like this:

const char* const Test::Name =  "Product Name";

An exception is integral constants, which are allowed to be in the class definition. An easy workaround is to use a static member function instead:

struct Test {
  static const char *Name() { return "Product Name"; }
};

Comments

0

Move the assignment of the string to the source/implementation file (.cpp).

Comments

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.