user749993
user749993

Reputation: 1

How to inherit appropriate class using dynamic binding?

I have a program which has abstract base class FILEPARSER that has two virtual methods read() and print(). Two classes inherited from this base class are: XMLPARSER and CONFIGPARSER that will implement methods.

the main program should accept the type of file "config" or "xml" and inherit the appropriate class for that type?

accepting the options from commandline.

Upvotes: 0

Views: 79

Answers (1)

sharptooth
sharptooth

Reputation: 170539

You'll have to explicitly construct the right class (pseudocode):

FileParser* parser = 0;
ParserType type = //retrieve the type you need
switch( type ) {
case ParserTypeConfig:
    parser = new ConfigParser();
    break;
case ParserTypeXml:
    parser = new XmlParser();
    break;
default:
    //handle error
};

//then at some point you use the created object by calling virtual functions
parser->read(blahblahblah);
parser->print();

// and then at some point you delete the heap-allocated object
delete parser;
parser = 0;

of course you should use a smart pointer to handle the heap-allocated object.

Upvotes: 2

Related Questions