开发者

Create derived class instance from a base class instance without knowing the class members

Is this scenario even possible?

class Base
{
  int someBaseMemer;
};

template<class T>
class Derived : public T
{
  int someNonBaseMemer;

  Derived(T* baseInstance);
};

Goal:

Base* pBase = new Base();
pBase->someBaseMemer = 123; // Some value set
Derived<Base>* pDerived = new Derived<Base>(pBase);

The value of pDerived->someBaseMemer should be equeal to pBase->som开发者_开发技巧eBaseMember and similar with other base members.


Why would you want to derive and pass the base pointer at the same time? Choose either, nothing stops you from having both. Use inheritance to do the job for you:

class Base
{
  public:
    Base(int x) : someBaseMemer(x) {}
  protected:      // at least, otherwise, derived can't access this member
    int someBaseMemer;
};

template<class T>
class Derived : public T
{
  int someNonBaseMemer;

  public:
  Derived(int x, int y) : someNonBaseMemer(y), T(x) {}
};

Derived<Base> d(42, 32); // usage

Though not the best of choices as design.


Why wouldn't you actually finish writing and compiling the code?

class Base 
{ 
public: // add this
    int someBaseMemer; 
}; 

template<class T> 
class Derived : public T 
{ 
public: // add this
    int someNonBaseMemer; 

    Derived(T* baseInstance)
        : T(*baseInstance) // add this
    { return; } // add this
}; 

This compiles and runs as you specified.

EDIT: Or do you mean that someNonBaseMemer should equal someBaseMemer?


Declare someBaseMemr as public or change the declaration from class to struct:

class Base
{
  public:
  int someBaseMemer;
};

OR

struct Base
{
  int someBaseMemr;
};

Remember that a class has private access to all members and methods by default. A struct provides public access by default.

Also, all derived classes should have public inheritance from Base.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜