Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!ut-emx!jamshid From: jamshid@ut-emx.uucp (Jamshid Afshar) Newsgroups: comp.lang.c++ Subject: Re: different member functions with same arg types? Summary: try making a new class Message-ID: <42908@ut-emx.uucp> Date: 22 Jan 91 05:31:41 GMT References: Organization: The University of Texas at Austin; Austin, Texas Lines: 61 In article montanaro@crdgw1.ge.com (Skip Montanaro) writes: > >I am writing a parser class for a small language. I'd like it to be able to >parse input from strings and files. The natural class interface (for me) is >something like: > class parser : public ... > { ... > public: > parse(char *string); > parse(char *filename); > ... > } > >I'm open to suggestions for alternate interfaces. > >Skip (montanaro@crdgw1.ge.com) This may be overkill for what you want, but why don't you make an abstract class, say SourceCode, that has pure virtual functions for everything that a parser will want to do with some source code. class SourceCode { public: virtual void init() = 0; virtual char getChar() = 0; virtual void putBackChar(char) = 0; virtual void skipWhiteSpace() = 0; virtual bool isAtEnd() = 0; virtual void close() = 0; ... }; Then derive new classes, 'SourceFromFile' and 'SourceFromString', from SourceCode and implement those virtual functions however they need to be implemented. SourceFromFile, for example, would have an ifstream object that is opened in init(). SourceFromString would have in addition to a 'const char *' (or better yet, a String), an index to indicate the current position in the string. Now, have the Parser constructor take a reference or a pointer to a SourceCode object so you can give Parser anything that can be derived from SourceCode. You might even be able to make SourceCode more intelligent, like a 'Token getToken()' function, or skipUntil(const char *) which could be implemented based on getChar(). The hard part, of course, is figuring out what functionality Parser needs from a SourceCode object. You also have to decide in which class to put some of the functionality you need. For example, does the parser build a token from getChar(), or is a source_code intelligent enough to break itself up into tokens? I don't think there are any "right" answers in situations like this-- it's all a matter of design. I would appreciate any comments on this approach. BTW, aren't there C++ versions of yacc or troff or something that would need to parse a file? What approach(es) do they use? It seems like the problem of compiling source code is an excellent candidate for an OO approach. Jamshid Afshar jamshid@emx.utexas.edu