Jump to content

member function of base class defined within derived class

- - - - -

  • Please log in to reply
1 reply to this topic

#1
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Hi

I don't understand the part in red at all. Okay. CountDn is a derived class. But this part as it stands

[COLOR=Red][B]Counter operator -- ()

         { return Counter(--count); }
[/B][/COLOR] simply means that it is a member function of base class Counter but is defined within the derived class. Isn't it so? In other words, if we had defined this function in the class Counter we would have used the same listing as we have used for it in the CountDn class. Please help me with it. Thanks.


#include <iostream>

#include <cstdlib>


using namespace std;


////////////////////////////////////////////////////////////////

class Counter

{

   protected:

      int count;


   public:

      Counter() : count(0)

         {  }

      Counter(int c) : count(c)

         {  }

      int get_count() const

         { return count; }

      Counter operator ++ ()

         { return Counter(++count); }

};

////////////////////////////////////////////////////////////////


[COLOR=Red][COLOR=Black]class CountDn : public Counter

   {

   public:[/COLOR][B]

      Counter operator -- ()

         { return Counter(--count); }

   };[/B][/COLOR]

////////////////////////////////////////////////////////////////


int main()

{

   CountDn c1;


   cout << "\nc1=" << c1.get_count();


   ++c1; ++c1; ++c1;

   cout << "\nc1=" << c1.get_count();


   --c1; --c1;

   cout << "\nc1=" << c1.get_count();


   cout << endl;

   return 0;

}


I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
The decision to do this makes sense in the nature of the derived class. Counter is assumed to be a class you use only for counting up. CountDn is another type of counter, so it should inherit all the functionality of Counter, with the added capability of counting down.

If your intention is to use Counter for counting up, and CountDn for counting down in addition to counting up, then this makes perfect sense. If that was not your intent, then you may want to restructure your code.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users