0

I'm trying to create static constant that will be named the same in different classes and can be accessed from other classes

I'm trying to access to the constant from other classes like that B::num

My code:

main.cpp

...
Ptr ptr;
A *a = C::make(ptr);

A.h

class A { //pure virtual
public:
 virtual void func()=0;
 virtual void func2()=0;
protected:
 Ptr ptr;
}

B.h

class B : public A {
 public:
  B();
  static unsigned char const num[2];
 ...
}

B.cpp

#include "B.h"
constexpr unsigned char B::num[]={0x4,0x5};
B::B(){..}

C.h

#include "A.h"
#include "B.h"
class C {
public: 
 static A* make(const Ptr &);
}

C.cpp

A *C::make(const Ptr &ptr){
    if(!memcmp(ptr.memory,B::num,sizeof(B::num))){
     ...
    }
}

errors

B.h file - error: from previous declaration 'B::num'

B.cpp file - error: redeclaration B::num differs in 'constexpr'

What is the problem? Thanks.

Fleev
  • 77
  • 8
Neet33
  • 241
  • 1
  • 5
  • 17
  • 4
    Please **[edit]** your question with an [mcve] or [SSCCE (Short, Self Contained, Correct Example)](http://sscce.org) – NathanOliver Aug 05 '15 at 12:37
  • 1
    See [Undefined reference to static constexpr char\[\]](http://stackoverflow.com/q/8016780/1708801) basically if it is odr-used you must define it outside the class ... although I can tell what the problem is @NathanOliver is correct you should provide a MCVE. – Shafik Yaghmour Aug 05 '15 at 12:37
  • Didn't you just forget the ending semicolon (`;`) after the class declarations? – Serge Ballesta Aug 20 '15 at 05:53

2 Answers2

0

First problem : you defined an unrelated, global a. The one you're trying to define is scoped inside the class(es).

static constexpr unsigned char class1::a[2] = {0x4,0x5};
//                             ^^^^^^^^

Second problem : defintions belong in .cpp files, not headers.

Quentin
  • 62,093
  • 7
  • 131
  • 191
0

Here is an example of static const a in 2 classes :

#include <iostream>

class class1 {
public:
    static unsigned char const a[2];
};

class class2 {
public:
    static unsigned char const a[2];
};

constexpr unsigned char class1::a[] = {0x4,0x5};
constexpr unsigned char class2::a[] = {0x4,0x5};

int main() {
    std::cout << static_cast<unsigned>(class1::a[0])
        << static_cast<unsigned>(class2::a[1]) << std::endl;
    return 0;
}

Note:

  • the declaration contains static and const and should be in a .h file
  • the definition constains constexpr and should be in a .cpp
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • errors: `.h file` `error: from previous declaration 'class1:a' `.cpp file` `error: redeclaration class1::a differs in 'constexpr'` – Neet33 Aug 18 '15 at 23:32
  • @Neet33: above code compiles and runs without a warning. If you have errors, you have changed it. How could I guess what is is **your** code??? You have already been asked to post a [mcve]. Without knowing your code, we cannot help you. – Serge Ballesta Aug 19 '15 at 05:54