0

I am out of ideas of how to fix this error. I've already defined the function in question but the compiler says I have not. Please help.

Here is the code:

class Parser{
public:
  virtual void parse(stringstream& ss) = 0;
};

class Main_Parser : public Parser{
public:
  Main_Parser(){
    cout << "new";
  }

  void parse(stringstream& ss){
    string s;
    ss >> s;
    cout << s;
  }
};

int main () {
  string s = "apple orange oracle";
  stringstream ss(s);
  Parser temp = Main_Parser();
  temp.parse(ss);
}

EDIT: I don't get how it is losing the information about method parse() if this is about splicing. Because I have already defined it in Parse class.

funnypig run
  • 182
  • 2
  • 9
  • 1
    Possible duplicate of [What is object slicing?](https://stackoverflow.com/questions/274626/what-is-object-slicing) – Algirdas Preidžius Jul 19 '18 at 15:53
  • No, that did not help. Still doesn't explain why I'm getting this error. I already have prase() defined in Parse class. So the information was not lost by defining this concrete version of Parser which is Main_Parser class. – funnypig run Jul 19 '18 at 15:59
  • Just change to `Parser *temp = new Main_Parser();`. – r3mus n0x Jul 19 '18 at 16:06
  • 2
    `Parser temp` there is no such thing. Parser is abstract. You cannot have a variable of type Parser, slicing or not. You want to read [Why doesn't polymorphism work without pointers/references?](https://stackoverflow.com/questions/15188894/why-doesnt-polymorphism-work-without-pointers-references) – n. m. could be an AI Jul 19 '18 at 16:09

1 Answers1

0

The problem is that the class Parser really don't have an implementation of parser function. It seems it like it is - a pure virtual function. By typing Parser* temp = new Main_Parser() you actually enables the compiler to expend his metaphore eyes to look for implementations in his derived connection classes.

Another way of doing this is to send to this pointer a reference for an existing derived class, like in this example:

int main () {
    string s = "apple orange oracle";
    stringstream ss(s);
    Main_Parser mp;
    Parser *temp = &mp;
    //or Parser *temp1 = static_cast<Parser*>(&mp);
    temp->parse(ss);
    return 0;
}

In this way, you don't have to worry about memory leak problem.

And the easiest way to solve the problem:

int main () {
    string s = "apple orange oracle";
    stringstream ss(s);
    Main_Parser mp;
    Parser &temp = mp; // Be smart and let the beginners an easy way to use your code
    temp.parse(ss);
    return 0;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Coral Kashri
  • 3,436
  • 2
  • 10
  • 22
  • Thank you for the detailed answer. I was working on a Java assignment earlier that day and it seems like my tired brain forgot about the fact that I had to use pointers. And I actually had done the same thing in a deleted part of the code. I guess I need to get used to c++ more. – funnypig run Jul 19 '18 at 23:56