inheritance - C++ How to initilize abstract base class reference element? -


my problem based on typical diamond hierarchy, not typical diamond problem.

class interface { public:     int value;      // somebigdata &data;      interface(int _value = 0) : value(_value) {};       virtual void function1() = 0;      virtual void function2() = 0;  };  class impone : public virtual interface { public:     void function1() { ++value; } };  class imptwo : public virtual interface { public:     void function2() { --value; } };  class device : public impone, public imptwo { public:     device() : interface(7) {};  }; 

there abstract interface defining many function (the example above simplified). there implementation classes implement few of these functions @ time. , finally, there non-abstract classes, class device above, implementing whole interface combining several implementation classes together.

now, problem this:

there integer element in interface class gets initialized class device , shared among implementation classes, far good. if remove = 0 interface(int _value = 0) constructor, whole system collapses because missing default constructor interface class, bit odd, because never gets called.

why bother me? suggested in code, interface class needs contain reference complex data structure (not owned class), shared among derived implementation classes. neither sensible nor possible specify default value reference.

so question is:

how correctly initialize interface class (reference) element such somebigdata &data suggested in code, can’t specify default value default constructor (which never gets called anyway)? or doing wrong?

you this:

class interface { public:     int value;      virtual somebigdata& getbigdata() = 0;     interface(int _value = 0) : value(_value) {};       virtual void function1() = 0;      virtual void function2() = 0;  };  class bigdataprovider : public virtual interface { public:     somebigdata& data_;     bigdataprovider(somebigdata& data) : data_(data) {}     somebigdata& getbigdata() { return data_; } };  class device : public bigdataprovider, public impone, public imptwo { public:     device(somebigdata& data) : bigdataprovider(data), interface(7) {} }; 

the same pattern used member value. interface "pure interface" , avoid diamond class layout overall.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -