简体   繁体   中英

conversion constructor, base class as a parameter?

If Derived derives from Base , does it make sense to define a conversion constructor like this?

Derived(const Base& b) : Base(b) {
    //...
}

Are there problems with the Derived copy constructor?

I'll specify my intent here. I have a Base class and three derived classes. I have objects for each derived class stored in lists, one for each type. I then have a file in which some the objects are stored, but as the base class. A line in the file indicates which type of derived class corresponds. My code should look in the correct list whether the object is present (using == operator inherited from the base class). Please tell me if there are better solutions as well.

I'm a little confused by what you're trying to achieve here but casting a base class object to a derived class one is almost certainly a bad idea.

If you have a collection of derived class objects stored as base class ones you don't need a "line in a file" identifying which type they actually are. Just define a virtual function in the base class (eg. GetType()) and implement it differently in each derived class. Or even better, to avoid the (if (obj.GetType() == ) style programming just have a single interface and provide different implementations in each derived class. The derived class knows perfectly well what it is and your top-level code probably doesn't need to know.

The proper solution for the underlying problem is a factory method: std::shared_ptr<Base> ReadObject(std::istream&); . This method can read the "type" line from your file and create the appropriate type object.

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