Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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->someBaseMember and similar with other base members.

like image 564
Aoi Karasu Avatar asked Feb 26 '10 21:02

Aoi Karasu


People also ask

Can we create derived class object from base?

No, it is not possible. Consider a scenario where an ACBus is a derived class of base class Bus.

How do you create a derived class of base class?

A base class is also called parent class or superclass. Derived Class: A class that is created from an existing class. The derived class inherits all members and member functions of a base class. The derived class can have more functionality with respect to the Base class and can easily access the Base class.

How do you access base class members in a derived class?

A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.

Can private members of base class become members of derived class?

Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.


2 Answers

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.

like image 100
dirkgently Avatar answered Sep 17 '22 11:09

dirkgently


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?

like image 43
MSN Avatar answered Sep 18 '22 11:09

MSN