• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

C++ inheritance bitchiness

Status
Not open for further replies.
Too used to Java (which does OO *right* :)... I can't get this working:

Code:
class Parsable {
  public:
   virtual void parse();
};

class Token: public Parsable {
  public:
    void parse();
    Token( string id );
    string getId();

  private:
    string id;
};

There are other classes that also inherit from parsable.
Later on, I have a vector of children of Parsables (no Parsables themselves). I want to iterate through the list, and do some checks on their properties. From those checks I can determine whether it's a Token or not. One of the things I want to do is get the id of the token (through getId).

The problem is, how do I convert the Parsable to a Token and maintain all the internal data? In Java it's easy, i can just say:

Token t = parsableList.at(i);

Or in the worst case scenario I can typecast it there:

Token t = (Token)(parsableList.at(i));

No luck in C++ though. Both give me errors.

I tried giving a getId() function to Parsable, but when I do that and call it. the Token's getId function won't override it.

Any suggestions?
 

Lathentar

Looking for Pants
You need to use pointers.

Parsable *p = new Token("MONKEY FUCKER");
Token *t = static_cast<Token>(parse);
 

NohWun

Member
Mister Zimbu said:
Too used to Java (which does OO *right* :)... I can't get this working:
...snip...
I tried giving a getId() function to Parsable, but when I do that and call it. the Token's getId function won't override it.

Any suggestions?

Make the getId() function virtual. You need something like that in order to differentiate the Parsables.
 

Jesiatha

Member
Not being able to do the conversion is the right thing, since a Parsable is not a Token. As mentioned, you can use RTTI's static_cast or dynamic_cast to get around it. Or you could add virtual methods to Parsable, as appropriate. Or create a new class which has members of the different subtypes of Parsable, and then do a switch based on that. Either way, what you're doing now is subverting the typing system, and is bad.

edit - accidentally posted mid writeup
 
Status
Not open for further replies.
Top Bottom