0

I am trying to implement the a map from the C++ STL as follows:

#include <string>
#include <iostream>
#include <map>
using namespace std;
#include "assembler.h"

// This Class makes use of the Map Template from the Standart Template Library
// All addresses are stored as numerical (Dec) integers

SymbolTable::SymbolTable() { // Constructor
    map <string, int> symbolTable;
    int address = 0;
}

void SymbolTable::addEntry(string symbol, int address) {
symbolTable[symbol] = address;
address++;
}

// Returns true if symbolTable already contains symbol
bool SymbolTable::contains(string symbol) {
    if (symbolTable.find(symbol) == symbolTable.end()) { return true; }
    else { return false; }
}

int SymbolTable::getAddress(string symbol) {
    return symbolTable[symbol];
}

I try to compile this with

c++ *.cpp -0 assembler.out

and I get the following error message:

symboltable.cpp:57:9: error: no viable conversion from 'mapped_type' (aka 'std::basic_string<char>') to 'int'
    return symbolTable[symbol];
           ^~~~~~~~~~~~~~~~~~~
1 error generated. 

I have searched for this error online and all I get is bug reports relating to the STL and I cannot figure out if those reports are the same problem I am having and if so how to get around it. Am I doing something wrong?

I have tried (probably stupidly) to typecast the offending line as

return (int) symbolTable[symbol];

Thank you for any help.

My header file declares the class as:

class SymbolTable {
public:
    SymbolTable();
    void addEntry(string, int); 
    bool contains(string);
    int getAddress(string);
private:
    map <string, string> symbolTable;
    int address;
};
jds
  • 604
  • 4
  • 16

1 Answers1

3

This:

SymbolTable::SymbolTable() { // Constructor
    map <string, int> symbolTable;
                        ^
                        ^

is a function-local variable, not a member variable. It is not the same as the symbolTable that you're accessing in e.g. getAddress, which presumably is a member variable. You haven't shown the class body, but my guess is that it's defined differently.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • Even though I declared it in the .h file? Sorry just started with C++ – jds May 22 '12 at 23:17
  • Also `int address = 0;` in the constructor. `address++;` in the `add` function also increments the wrong `address` variable. – Mooing Duck May 22 '12 at 23:17
  • @Justin: Yes. Local variables hide member variables. – Oliver Charlesworth May 22 '12 at 23:17
  • @Justin: That's not how constructors work, your code creates a new variable local to the function that has the same name as your class member, and then does nothing with it. Read up on ["initializer lists"](http://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list) – Mooing Duck May 22 '12 at 23:18
  • @Justin, the term to google about local and class members is "shadowing". – chris May 22 '12 at 23:18