Note that there are some explanatory texts on larger screens.

plurals
  1. POLearning inheritance
    text
    copied!<p>I am trying to understand inheritance and I need some help building two classes. The fist one is called A, the second one is called B. A has one private integer value "m_a". It has two constructors, the default one sets m_a to 5. and another one which takes as an argument an integer called m and sets m_a's value to m. As for member functions it will have two. The first one will return m_a. The second one will print "Hello from A!". Let's move on to B. B will have a private string m_s. A default constructor which will set m_s to "asd" or to anything other than an empty string and a constructor which will take as an argument a string and set m_s to it's value. As far as functions go, firstly B will have a function that will return m_s. It will have a function which will have the same name as the print "Hello from A" function in A which will override it and it will printout "Hello from B!" instead (is that polymorphism ?).</p> <p>Those are the classes needed. I have the following questions (I will post what I have created below) Firstly, is there any way I can get to the private data fileds from the base class. For example let's say I want to take the m_s variable, add it to another one and print out their sum. Is that possible ? (and how) </p> <p>Also when I try to create a class with a constructor different from the default one I get errors. I am obviously doing something wrong. The question is what.</p> <p>I think those are all of my questions for now, so it is time for me to post the source code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class A { private: int m_a; public: A(){m_a = 5;} A(int m) { m_a = m; } void pm() { cout &lt;&lt; "Hello from A!" &lt;&lt; endl; } int get_a() { return m_a; } }; class B : A { private : string m_s; public: B(){m_s = "asd";} B(string s) { m_s = s; } void pm() { cout &lt;&lt; "Hello from B!" &lt;&lt; endl; } string get_s() { return m_s; } }; int main() { A a(10); a.pm(); cout &lt;&lt; a.get_a() &lt;&lt; endl; B b("asd"); b.pm(); cout &lt;&lt; b.get_s() &lt;&lt; endl; cout &lt;&lt; b.get_a() &lt;&lt; endl; return 0; } </code></pre>
 

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