I’m having an issue with the wrong method being called. In my program, I have 3 classes: symbol, nonTerminal, and terminal. nonTerminal and terminal are both subclasses of symbol.
In my program, I only ever create a terminal or nonTerminal. Here are some condensed versions of each class:
#ifndef SYMBOL_H
#define SYMBOL_H
#include <vector>
class terminal;
using namespace std;
class symbol {
public:
virtual vector<terminal> getFirstSet();
};
#endif
_
#ifndef NONTERMINAL_H
#define NONTERMINAL_H
#include "symbol.h"
#include "terminal.h"
#include <vector>
using namespace std;
class terminal;
class nonTerminal: public symbol {
public:
vector<terminal> getFirstSet();
};
#endif
_
#ifndef TERMINAL_H
#define TERMINAL_H
#include "symbol.h"
#include <vector>
using namespace std;
class terminal: public symbol {
public:
vector<terminal> getFirstSet();
};
#endif
I have this function:
bool addFirst(symbol s) {
vector<terminal> first = s.getFirstSet();
//....
}
However, anytime I call it with a terminal or nonTerminal, it always uses the symbol::getFirstSet method. How can I get it to call the correct nonTerminal::getFirstSet or terminal::getFirstSet method?
Your function addFirst is receiving your object by value. What this means is that:
Every time you call addFirst() a new symbol object is created and copied from existing terminal or nonTerminal.
Whenever said copy occurs, the resulting object is neither terminal nor nonTerminal, but their base class – symbol.
To counter it, and to avoid copying the object, try passing your object by reference: