Chase W.
Chase W.

Reputation: 1413

c++ declaring a class's const member object

I'm referring to this stackoverflow post:

When I build the following code, I get: "duplicate symbol for architecture x86_64". I've been googling for the past couple of hours, but have not found anything to help. Any suggestions?

#ifndef __lexer__lexer__
#define __lexer__lexer__

#include <stdio.h>
#include <string>

namespace Tag{
  const int AND = -1,
  OR = -2;
}

class Token{
public:
  std::string Name;
  std::string Type;
  std::string Value;
  int Tag;
  Token(std::string name, std::string type, std::string value, int tag){
    Name = name;
    Type = type;
    Value = value;
    Tag = tag;
  }
};

class Word : public Token{
public:
  Word(std::string name, std::string type, std::string value, int tag) : Token(name, type, value, tag){}
  static const Word AND;
};

const Word Word::AND = *new Word("and", "logical", "&&", Tag::AND);

#endif /* defined(__lexer__lexer__) */

The code:

const Word Word::AND = *new Word("and", "logical", "&&", Tag::AND);

Is what is giving me the problems.

Upvotes: 0

Views: 75

Answers (2)

Andrew Lazarus
Andrew Lazarus

Reputation: 19362

The short answer is you don't want to do the definition (as opposed to the declaration) in a .h file. Your error comes when the .h file is included in more than one other file.

A slightly longer answer is that your *new idiom is unnecessary and probably wastes a small amount of storage.

const Word Word::AND("and", "logical", "&&", Tag::AND);

will invoke the same constructor.

And an even longer answer is that Tag should be an enum, and you do not want to pass std::string by value. Maybe you are coming from another language: you need to learn about pass by reference and const reference.

Upvotes: 4

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12362

The initialization code belongs in a .cc file, not in the header. In the header every compilation unit that includes it would create a new one and then the linker rightfully complains about duplicates.

Upvotes: 2

Related Questions