Polymorphism

This is a discussion on Polymorphism within the C++ Programming forums, part of the General Programming Boards category; Hi, I was wondering what is Polymorphism? I have been reading ebooks and websites but I just don't understand when ...

  1. #1
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629

    Polymorphism

    Hi, I was wondering what is Polymorphism? I have been reading ebooks and websites but I just don't understand when to implement it or how for that matter.
    Do I use virtual functions or function polymorphism ?

    I know that in order to use polymorphism, you might have to inherit from other class.
    I created a super class, and derived classes. Because the derived classes have common attributes with each other..
    So what I did was create a virtual function to enforce restrictions in the positions of the each child object instances. For example class 1 object might check to see if age is between 1-4 and the other class to see if age is between 4-10.

    Which brings me to the question of virtual functions. What is the point of it? I will just give an example class
    Code:
     
    
    class Animal:
    {
         private: 
            int numFeet ;
            int Age ; 
            int height ,weight ;
        public: 
           Animal()
          {
               numFeet = 0 ;
               Age = 0 ;
               height = 0 ;//and so on
           }
           virtual void setAge(int) =0; 
    
    }
    class Dog:public Animal
    {
         public: 
            Dog::setAge(int x) 
           {
                 if(x>1 && x <4 )
                {
                    Age = x ; 
                }
               else
              {
    
                    Age = 0 ;
               }
           } 
    }
    }
    class Human:public Animal
    {
         public: 
            Human::setAge(int x) 
           {
                 if(x>4 && x <10 )
                {
                    Age = x ; 
                }
               else
              {
    
                    Age = 0 ;
               }
           } 
    }
    from that because the way setAge() inherited from Animal is defined I could instead
    create each implementation of setAge() in the different classes without bothering with a virtual function, it looks like the same thing to me.
    if that is true the only thing I can see with a virtual function is that it is a way of making a superclass or abstract class from being instantiated.

    while I at least have some understanding of inheritance I don't get polymorphism
    i have a super class and derived classes inherit from them. while they perform the same operation, i want them to be able to change the operation they perform- where I am sure polymorphism comes in, changing their behavior.

    Code:
    class Thing:
    {
        private :
            int h,w;
            bool isTrue ; 
       public:
           draw(int x1,int x2) ;
           draw(int x1,int y1,x2,y2) ;
           draw(int x1,int y1,x2,y2,x3,y3) ;
    
    }
    class Child1:public Thing
    {
          
    }
    class Child2:public Thing
    {
    }
    from the above code, each derived class should be able to change how they draw itself, a triangle will use the 3rd draw, a rectangle the first draw() and so on.
    So i used function polymorphism. Which is the easiest way I could implement it.
    But how do I use one function draw() to able to draw all the shapes just using the draw() ?
    Please, i need to understand poly.

  2. #2
    Registered User
    Join Date
    Nov 2007
    Posts
    46
    I'm sure someone else will be better at explaining your first few questions, because I'm generally bad at explaining things. But I can however provide a suggestion for your last question:

    Wouldn't the logical solution be to have a Shape(Named it Shape instead of Thing) class like this?:

    Code:
    class Shape {
    public:
    	virtual ~Shape();
    	virtual void Draw() = 0;
    };
    Then the derived classes like this:

    Code:
    class Rectangle : public Shape {
    public:
    	Rectangle( int left, int top, int right, int bottom );
    	void Draw(); 
    private:
    	int left_, top_, right_, bottom_;
    };
    
    class Triangle : public Shape {
    public:
    	Triangle( int x1, int y1, int x2, int y2, int x3, int y3 );
    	void Draw();
    private:
    	int x1_, y1_, x2_, y2_, x3_, y3_;
    };
    Then if you want to move these around, add a pure virtual "Move" or "Translate" function to the base class, taking offset parameters x and y, and then implement these in the derived classes? Similarly for rotation and scaling functions. And of course you can just follow the same procedure I used for the Triangle and Rectangle example for other shapes, such as circles for example.

    I know I didn't fill in the function bodies, but it should be pretty simple. Also, consider making the Draw function const, because there shouldn't be any logical reason for a Draw function to change the state of the Shape should there?

  3. #3
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629
    Quote Originally Posted by JacobN View Post
    I'm sure someone else will be better at explaining your first few questions, because I'm generally bad at explaining things. But I can however provide a suggestion for your last question:

    Wouldn't the logical solution be to have a Shape(Named it Shape instead of Thing) class like this?:

    Code:
    class Shape {
    public:
    	virtual ~Shape();
    	virtual void Draw() = 0;
    };
    Then the derived classes like this:

    Code:
    class Rectangle : public Shape {
    public:
    	Rectangle( int left, int top, int right, int bottom );
    	void Draw(); 
    private:
    	int left_, top_, right_, bottom_;
    };
    
    class Triangle : public Shape {
    public:
    	Triangle( int x1, int y1, int x2, int y2, int x3, int y3 );
    	void Draw();
    private:
    	int x1_, y1_, x2_, y2_, x3_, y3_;
    };
    Then if you want to move these around, add a pure virtual "Move" or "Translate" function to the base class, taking offset parameters x and y, and then implement these in the derived classes? Similarly for rotation and scaling functions. And of course you can just follow the same procedure I used for the Triangle and Rectangle example for other shapes, such as circles for example.

    I know I didn't fill in the function bodies, but it should be pretty simple. Also, consider making the Draw function const, because there shouldn't be any logical reason for a Draw function to change the state of the Shape should there?
    Thanks for quick reply. I need to have a Thing class but I did think of creating a Shape class and three subclasses to derive from the Shape class. and making them member objects of the Thing class. But I was afraid to confuse myself furthermore.

    the thing is for the Human or Dog.
    I could decide in my start up program that I want a dog to draw a rectangle to the screen and also be able to draw a circle or triangle.
    and the Human should be able to do the same. I just can't see how to do so, i am writing down to see how to do it. I will try and do what you said.
    Thanks for reply

  4. #4
    Registered User
    Join Date
    Nov 2007
    Posts
    46
    Well, you could make the Thing class hold a vector of pointers to Shapes, like this:

    Code:
    class Thing {
    public:
    	/* Constructors and public member functions */
    	void Draw();
    private:
    	/* Other members */
    	std::vector<Shape*> Shapes_;
    };
    Then you can use this Shapes_ vector to hold all the shapes a Thing of a specific type is made up of. The advantage of using polymorphism in this case is that you can shove any shape you wish, as long as it's derived from Shape into the Shapes_ vector, and the underlying system will then make sure to call the correct Draw function for the given shape, in the vector, for you, if you were to do something like:

    Code:
    Shapes_[0]->Draw();
    Then if at position 0 there was a Rectangle, it would call the Draw function of a Rectangle, or if it was a Triangle, the one for a triangle, etc. etc.

    This of course leads directly to how you can implement the Draw function for a Thing in a very straight forward way, but I'll let you work on that yourself.

    I should probably also mention that now you might also be moving into the area of dynamically allocating memory, so if you know about that already, good, if you don't, read up on it, because you will most likely have to "new" what you put into this Shapes_ vector, and then later "delete" it again, probably in the destructor of the Thing class. You can also consider using a so-called "smart pointer", but I'm not sure if that would be too many concepts at once.
    Last edited by JacobN; 10-31-2010 at 06:52 AM.

  5. #5
    Registered User
    Join Date
    Oct 2010
    Posts
    45

    Thumbs up

    Quote Originally Posted by Eman View Post
    Hi, I was wondering what is Polymorphism? I have been reading ebooks and websites but I just don't understand when to implement it or how for that matter.
    Do I use virtual functions or function polymorphism ?

    I know that in order to use polymorphism, you might have to inherit from other class.
    I created a super class, and derived classes. Because the derived classes have common attributes with each other..
    So what I did was create a virtual function to enforce restrictions in the positions of the each child object instances. For example class 1 object might check to see if age is between 1-4 and the other class to see if age is between 4-10.
    I think your making it more confusing than it needs to be, and others can correct me (please do!) if I'm wrong in my lower intermediate thinking here... Instead of having the objects check themselves, what you want to do is create a different object based on a piece of information (in your case of a child, its age).

    Say: Virtual Human class, derived Toddler, derived GradeSchooler

    Making Human virtual prevents the user from ever creating an instance of one. Just like you would never make an Animal or a Car, but you would make a Tiger or a PT Cruiser, which are specific instances of objects as related to real world ideas/things.

    However, having Human (Car, Animal, ...) allows you to decide when the program RUNS what type of Human you are making. Such as:

    Code:
     
    if(age < 4)
        Human * Child = new Toddler; 
    else
        Human * Child = new Gradeschooler;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Polymorphism - "pointers" or "references"?
    By Petike in forum C++ Programming
    Replies: 10
    Last Post: 06-04-2009, 05:06 PM
  2. Polymorphism
    By GiN0 in forum C++ Programming
    Replies: 1
    Last Post: 03-23-2007, 06:18 PM
  3. Inheritance and Polymorphism
    By bench386 in forum C++ Programming
    Replies: 2
    Last Post: 03-18-2004, 09:19 PM
  4. change sorting method using polymorphism
    By Forever82 in forum C++ Programming
    Replies: 2
    Last Post: 07-31-2003, 01:21 PM
  5. Polymorphism & Overloaded Operators :: C++
    By kuphryn in forum C++ Programming
    Replies: 2
    Last Post: 09-13-2002, 08:40 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21