简体   繁体   中英

How to access derived class fields using polymorphism in c++?

i have a simple parameter model class which derives from the base class, like this:

class IParams
{
    ....
};

class QEParams : public IParams
{
    ....
};

I also have executor class which derives from the base class containing IParams field.

class IExecutor
{

protected:

    IParams parameters;

public:

    virtual inline void initialize(IParams parameters) = 0;
    virtual IParams& execute() = 0;

};

class QEExec : public IExecutor
{

public:

    virtual void initialize(IParams parameters) override;
    virtual QEParams& execute() override;

};

Class QEExec should hold QEParams in parameters field. How to access QEParams members in QEExec class? Should I cast the type of parameters to QEParams?

While I agree, that you should probably overthink your design, here is how you do what you want to do:

If you want parameters to be able to house either an object of type IParams and of type QEParams the standard way to do this, is to use a pointer or parameter to base class. You cannot let parameters have type IParams and expect it to fit also an object of type QEParams since those two have a different memory layout (and probably a different size) so they necessarily cannot be at the same place.

It depends a bit on the structure of your code, how exactly you want to do this. If the Executor owns the parameter, the best type would be std::unique_ptr<IParams> . Otherwise you probably want to use either IParams* , IParams& or std::shared_ptr<IParams> depending on how you manage the lifetime of this object. The argument to initialize should be of the same type (and use move semantics if your working with std::unique_ptr ).

To access QEParams ' members, you have to use dynamic_cast . But be very careful with this.

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