Search code examples
c++c++11recursionostream

Recursive ostream function c++


I have a class which has children of the same type, and I want to get data from them all with a function that takes an ostream reference. So far I have this code, but I am getting an error:

"invalid operands to binary expression ('ostream' (aka 'basic_ostream') and 'ostream')"

ostream& print(ostream& myOstream) {

    if(child!=nullptr){
        myOstream << child->write(myOstream);
    }

    myOstream << " " << objectData << " ";

    return myOstream;
}

I gather there's a problem with the functions return value and printing that to the ostream? I've been trying to fix this for quite a while so would appreciate any help! Thanks.


Solution

  • You shouldn't output the result of printing the child:

    if (child != nullptr){
        child->write(myOstream);
    }