Note that there are some explanatory texts on larger screens.

plurals
  1. POInheriting and overriding ostream operator in C++
    primarykey
    data
    text
    <p>I've been trying to find an answer to this, but no one seems to have exactly the same problem as I do.</p> <p>I am working with several derived classes. The ostream operator &lt;&lt; for each of these should print out some things common to each, and some things specific to each. Later on, I would like to further derive from these derived classes, and again the new derived classes need to print out some things that are in the "generations" above them.<br> For example:</p> <p>The Base class .h file</p> <pre><code>class Base { int FirstClassNumber; //The declaration I'm currently working with, that a friend gave me //I'm pretty sure my problem lies here. public: friend ostream&amp; operator &lt;&lt; (ostream&amp; os, const Base &amp;base) { base &lt;&lt; os ; return os; } virtual void operator &lt;&lt; (ostream&amp; os) const = 0; }; </code></pre> <p>The Base.cpp file includes these lines:</p> <pre><code>void Base::operator &lt;&lt; (ostream&amp; os) { os &lt;&lt; FirstClassNumber; } </code></pre> <p>Then I derive: (FirstDerived.h)</p> <pre><code>class FirstDerived : Public Base { int SecondClassNumber; }; </code></pre> <p>FirstDerived.cpp:</p> <pre><code>FirstDerived::operator &lt;&lt; (ostream&amp; os) { os &lt;&lt; "The first Number is: //This is the line that isn't working - someone else gave me this syntax &lt;&lt; Base::operator&lt;&lt; &lt;&lt; "The second number is" &lt;&lt; SecondClassNumber; } </code></pre> <p>Then I want to derive:</p> <pre><code>class SecondDerived: Public FirstDerived { int ThirdClassNumber; }; </code></pre> <p>Second.cpp:</p> <pre><code>FirstDerived::operator &lt;&lt; (ostream&amp; os) { os &lt;&lt; FirstDerived::operator&lt;&lt; &lt;&lt; "The third number is " &lt;&lt; ThirdClassNumber; } </code></pre> <p>I think the problem is most likely either the declaration in the very start of the program, or the lines like <code>Base::operator&lt;&lt;</code>.</p> <p>Another possibility is that I'm not redeclaring it in the .h file of every inherited class. Should I be, and if so what syntax should I use? </p> <p>It was suggested to me to use the <code>static_cast</code> method, but my professor (the one who wrote the assignment, and therefore won't give us too much help with it) said that there's a better way to do it. Any suggestions?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload