Question

Something like this must have been asked on SO before, but I failed to track down an answer directly addressing the below. It is a very basic question, but, away from my books, I'm blanking.

I define a parent and child type class:

class token{...};  

class word: public token{...};  

Class token shares a variable with word; word further refines token. Neither class is virtual.

I have a helper function of the following signature, with representative creation code indicated:

token  
maker()  
{  
...  
case ...: // (1)
  return token(...);
case ...: // (2)
  return word(...);
...
},  

the idea being obviously that it creates the appropriate type, and returns it as a token.

I mean to use the returned object by statically assigning it to a token type, with dynamic resolution to the true type (word or token) when appropriate, as in

token t = maker(); // I want to be able to use the methods of word, if 
                   // maker actually made a word (true polymorphic behavior)

I realize that this should be by pointer or reference to enable polymorphism, and that in the current design maker() slices word types to token types; but am blanking on how to do adjust the above best to achieve my goal. Yes, I am embarassed.

Was it helpful?

Solution

For polymorphism to work, you need virtual functions and must work with pointers and references, not the type itself.

Case in point:

token* maker(...) {
    ...
    switch(...) {
    case ...: // (1)
        return new token(...);
    case ...: // (2)
        return new word(...);
    }
    ...
}

Though perhaps you should use std::unique_pointer<token> for returns and parameters which assign ownership. Also look at std::shared_pointer. Delete them with:

delete pToken;

Obviously, you need a virtual dtor in token itself.

OTHER TIPS

Return a std::unique_ptr<token> in maker. Although I have to say that when you say

Class token shares a variable with word; word further refines token. Neither class is virtual.

I am not sure if public inheritance is appropriate. It sounds more that word uses token to share implementation because there are not virtual functions.

first, use pointers. second, use dynamic_cast<>

change maker to return pointer and use it like:

token* t = maker();
if( word* w = dynamic_cast<word*>(t) )
{
    // if you get here, w is a valid word
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top