Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The member variable <code>Circle::r</code> is never set, the local variable <code>r</code> in <code>main()</code> is set via <code>cin</code> but never used.</p> <p>Something like this may be want you want:</p> <pre><code>class Circle { public: Circle(int a_radius) : r(a_radius) {} // function that calculates the area of a circle float circle_area(int r) { area = 3.14 * (r*r); return area; } // end function circle_area void display_msg() { cout &lt;&lt; "Area: " &lt;&lt; circle_area(r) &lt;&lt; endl; } // end function display_msg private: float area; int r; }; // end class Circle int main(void) { int r; cout &lt;&lt; "Radius of circle: "; cin &gt;&gt; r; Circle circle_calc(r); circle_calc.display_msg(); } </code></pre> <p>The variable <code>int r</code> declared in <code>main()</code> is not related to the member variable <code>r</code> in class <code>Circle</code>, even though they have the same name: they are two different variables.</p> <p>EDIT:</p> <p>Further refinement of class <code>Circle</code>:</p> <pre><code>class Circle { public: // Constructor. Circle(int a_radius) : r(a_radius) {} // function that calculates the area of a circle float circle_area() { return 3.14 * r * r; } void display_msg() { cout &lt;&lt; "Area: " &lt;&lt; circle_area() &lt;&lt; endl; } private: int r; }; // end class Circle </code></pre> <p>Changes:</p> <ul> <li><code>area</code> does not need to be a member variable (as stated by Fred Larson)</li> <li><code>r</code> is not required to be passed to <code>circle_area()</code> member function as <code>r</code> is a member variable, so <code>circle_area()</code> has access to it</li> </ul>
 

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