简体   繁体   中英

C++: Accessing variables present only in one of the derived classes

void func1()
{
}

class Base
{
    public:
        virtual void memfunc() = 0;
};
class DerivedA: public Base
{
    public:
        virtual void memfunc() = 0;
};
class Derived1: public DerivedA
{
    public:
        void memfunc()
        {  
            func1();
        }
};
class Derived2: public DerivedA
{
    public:
        int* pbuf;
        int val;

        void func2(int* pbuf,int val)
        {
                /* update pbuf depending on the value of val*/
        }

        void memfunc()
        {  
            func1();
            func2(pbuf,val);
        }
};
class user{
    public:
    Base* mBase;
    void userfunc()
    {
        mBase = f(); //Object pointer to Derived1/Derived2 will be assigned based on dynamic loading;
//Before calling the below func, I Need to assign value to the 'val' variable of the class 'Derived2'
        mBase->memfunc();
    }

};
int main()
{
    user ouser;
    ouser.userfunc();
    return 0;
}

The variables val and pbuf are present in Derived2 only. How can I assign values to them in userfunc/main as I don't know if the object mBase would point to Derived1/Derived2 .

You can use dynamic_cast and check for NULL, which will be returned if the object isn't of type Derived2. If the cast succeeds, you can use all methods of Derived2.

Use a dynamic_cast in userfunc() and test for Derived2 , ie

Derived2* p = dynamic_cast<Derived2*>(mBase);
if (p) // this is NULL if the above fails.
{
  // initialize...
}

If val and pbuf are present only on Derived2, then you must have some way to identify them. You would need to create an enum Base::Type { Derived1, Derived2 }, set them on your derived classes, and test in main. Then, you can cast mBase to Derived2 if it is of that type, and set val.

If you are sure of the concrete type of your class you can use a dynamic_cast. Anyway that's a bad practice. The purpose of using a base abstract class reference is to hide internal details and specific implementations issues.

If you need to do so, maybe you can add a getProperty()/setProperty() method to your base class. Something like:

class Base
{
    public:
        virtual void memfunc() = 0;
        virtual void setProperty(String name, Property prop);
        virtual Property getProperty(String name);
};

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