简体   繁体   中英

C++: use a pure virtual function in a non-virtual function

I'm trying to make a base class that defines the interfaces for all derived classes.

I'd like to have a function that allows one to read a config file for that class, which is working out pretty smooth using boost::property_tree . Let's call this function readConfig . This would have to be defined in each derived class, so I made it pure virtual.

I would like to overload the readConfig function in the base class where every overloaded function in the base class eventually calls the pure virtual form, eg:

class Base
{
    // ...
    void readConfig(string, string);                                 // read config from file
    virtual void readConfig(boost::property_tree::ptree, string) =0; // read config from ptree
}

void Base::readConfig(string filename, string entry)
{
     boost::property_tree::ptree pt;
     read_xml(filename, pt);
     readConfig(pt, entry);       // <= Calling pure virtual function!
}

Basically the string version is just a quick wrapper for the pure virtual form. When I compile this, I get an error:

no known conversion for argument 1 from std::string to boost::property_tree::ptree`

So it seems, the nonvirtual function (from Base ) is not recognized as being available. I checked that my derived class definition is ok:

class Deriv : public Base
{
    // ...
    void readConfig(boost::property_tree::ptree, string); // implement virtual, error is on this line
}

void Deriv::readConfig( boost::property_tree::ptree pt, string entry)
{
    //...
}

note that I omitted a lot of const -correctnes, pass by reference etc. to make the code a bit more readable.

What can I do to fix this? Is using a pure virtual member-function in a non-virtual function a good idea?

See the FAQ item titled "What's the meaning of, Warning: Derived::f(char) hides Base::f(double)?" available at numerous mirrors of the FAQ, including the original English version of the FAQ .

It is often a good idea to check the FAQ before posting.

It is quite possible that you will also find helpful (although not for the immediate problem) the FAQ item titled "Okay, but is there a way to simulate that behavior as if dynamic binding worked on the this object within my base class's constructor?", plus that if that becomes relevant, then you might also be interested in reading my blog article about the DBDI problem .

Obvious typo is obvious:

virtual void readConfug

instead of

virtual void readConfig

Also, what you're implementing is called template method pattern , FYI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM