Same as this : Creating an instance of a derived class from an instance of the parent class
Except :
- C++ (I do not know C#, this was just what the SO research yielded)
- 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++ ?
If we ignore the fact that you're planning to do this to
std::cout, in your specific example you could do this:Or this: (slightly less optimal, but is usable outside of consturctors of
B)But if your goal is to customize the behavior of
std::cout, this is not the best option. The state ofstd::coutis not copyable, a better option would be to create your own independentstd::ostream.Or, even better option would be to forget about output streams. C++20
std::formatis most likely the future of text output. Consider creating your own function wrappingstd::formatand printing the result.