Thread: polymorphism and inheritance

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by stewie griffin View Post
    At first I didn't use switch:
    Code:
    ostream& operator << (ostream& os, const Drawing& drw)
     {
         for(int i=0; i<drw.size_;i++)
              if (!(drw.drawing_[i].is_empty()))
     	os << drw.drawing_[i]<<endl;
         return os<<endl;
     }
    I have operator << for each type of shape that prints what it needs
    I thought that was enough
    The problem with overloaded operators is that they are not virtual. So to solve that, I'd suggestion you do something like this:
    Code:
    class Shape
    {
    ...
      public:
    ...
         virtual void Draw(ostream& os) = 0;
    };
    
    class Line : public Shape
    {
    ... 
       public:
    ...
         virtual void Draw(ostream& os);
    };
    
    void Line::Draw(ostream &os)
    {
        ... do your ACTUAL drawing for line, using basic << operator.
    }
    
    ostream& operator << (ostream& os, const Shape& sh)
     {
         sh.Draw(os);
         return os;
     }

    That way, each drawing can do it's own thing, but you can still use a generic form with << .

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    20
    and what if I can't use virtual functions (exercise restrictions)?

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by stewie griffin View Post
    and what if I can't use virtual functions (exercise restrictions)?
    That's sort of like being required to ride a bicycle but not allowed to use the pedals. A class hierarchy often makes little sense if virtual functions aren't allowed.

    As others have said, it is necessary to convert base class pointers/references to the correct type.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. inheritance, polymorphism, and virtual functions
    By cs_student in forum C++ Programming
    Replies: 8
    Last Post: 08-04-2008, 08:47 AM
  2. Replies: 8
    Last Post: 01-13-2008, 05:57 PM
  3. Polymorphism, inheritance and containers
    By musicalhamster in forum C++ Programming
    Replies: 6
    Last Post: 11-27-2007, 10:23 AM
  4. Inheritance and Polymorphism
    By bench386 in forum C++ Programming
    Replies: 2
    Last Post: 03-18-2004, 10:19 PM
  5. inheritance and polymorphism uses...
    By tetra in forum C++ Programming
    Replies: 5
    Last Post: 05-06-2003, 05:30 PM