C++ : Create instance of derived class from instance of parent class without constructor/further knowledge

98 views Asked by At

Same as this : Creating an instance of a derived class from an instance of the parent class

Except :

  1. C++ (I do not know C#, this was just what the SO research yielded)
  2. I do not want to write the list of all parameters that the existing instance has and copy them over. I'd like to do that in one fell swoop, with this code not needing an update when the parent class changes.

In case this is an XY problem : I want to create my own instance of std::cout from a derived class of ostream that I plan to create, which will have some extra methods and also overridden operators that will allow me to do more things, among which the ability to elsewhere mute the output, all code passing data to cout staying the same.

E.g. mutableCout << someData << "," << someData; stays the same but elsewhere I can write mutableCout.mute()

But I am generally interested in this question, as far as C++ is concerned.

Is it feasible in C++ ?

I expect it would look something like this :

class A
{
    A(<...>);

    SomeTypeA m_a;
    SomeTypeB m_b;
    .
    .
    .
    SomeTypeZ m_z;
}

class B : public A
{
public:
    B(A instanceOfA, someValueB)
    {
        <...copy everything from instanceOfA...>;

        valueB = someValueB;
    }
    void set() {valueB = true};
    void unset() {valueB = false};

private:
    bool valueB;
}

extern A instanceOfA;

B instanceOfB = B(instanceOfA, false);
...
instanceOfB.set();

The part that says <...copy everything from instanceOfA...> is the one I want to discuss, if at all feasible. I do not want to write :

m_a = instanceOfA.m_a
m_b = instanceOfA.m_b
....
m_z = instanceOfA.m_z

Question : Is it feasible in C++ ?

1

There are 1 answers

0
HolyBlackCat On

If we ignore the fact that you're planning to do this to std::cout, in your specific example you could do this:

B(A a) : A(std::move(a)) // `move` is optional
{
    // ...
}

Or this: (slightly less optimal, but is usable outside of consturctors of B)

B(A a)
{
    A::operator=(std::move(a)); // `move` is optional
    // ...
}

But if your goal is to customize the behavior of std::cout, this is not the best option. The state of std::cout is not copyable, a better option would be to create your own independent std::ostream.

Or, even better option would be to forget about output streams. C++20 std::format is most likely the future of text output. Consider creating your own function wrapping std::format and printing the result.