Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If the intention is that for instances of CheckingAccount accounts the versions which use a fee is called, then you want to use virtual methods.</p> <p>A virtual method is a method decalared (at least in the base class) as "virtual", and has the same name and signiture in any derived classes. When a virtual method is called, it will call the "most derived" version for the instance.</p> <p>To do this just declare "void creditBalance(double);" and "void debitBalance(double);" virtual (ie "virtual void creditBalance(double);" and "virtual void debitBalance(double);". Then in CheckingAccount rename "feeCreditBalance" and "feeDebitBalance" to "creditBalance" and "debitBalance".</p> <p>EDIT: Simple example.</p> <p>Header</p> <pre><code>class Base { public: Base(int x); //declare virtual so that derived classes may overide it virtual void sayHello(); protected: int x; }; class Derived : public Base { public: Derived(int x, int y); //overide Base::sayHello(). the virtual keyword here is optional. virtual void sayHello(); protected: int y; }; </code></pre> <p>Cpp</p> <pre><code>Base::Base(int x) :x(x) {} Derived::Devired(int x, int y) :Base(x), y(y) {} void Base::sayHello() { std::cout &lt;&lt; "Hello from Base!" &lt;&lt; std::endl; std::cout &lt;&lt; "X = " &lt;&lt; x &lt;&lt; std::endl; } void Derived::sayHello() { std::cout &lt;&lt; "Hello from Derived!" &lt;&lt; std::endl; std::cout &lt;&lt; "X = " &lt;&lt; x &lt;&lt; " Y = " &lt;&lt; y &lt;&lt; std::endl; } int main() { Base a(5); a.sayHello();//"Hello from Base!..." Derived b(10, -20); b.sayHello();//"Hello from Derived!..." Base *c = &amp;b;//take pointer to b, reference would also do c-&gt;sayHello();//"Hello from Derived!..." because its a Derived instance, eventhough its a Base variable. } </code></pre> <p>You can then derive from Derive again (class DerivedAgain : public Derived) and also overload the functions again.</p> <p>You can also derive multiple subclasses from Base, which can each have their own overrides for the virtual methods, just like I did for the Derived class.</p> <p>EDIT2: Added variables to example and how to use initialiser list to initialise the base class and member variables.</p>
 

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