Thread: Polymorphism - "pointers" or "references"?

  1. #1
    Beginning game programmer Petike's Avatar
    Join Date
    Jan 2008
    Posts
    64

    Question Polymorphism - "pointers" or "references"?

    Hi,
    I have a little problem about "polymorphism" in c++.

    Just for beginning:
    =================================================
    In "Java" language, there are all the objects (or types) accessed by pointers (we don't write them manually by hand but "they are there").
    For example in Java, this code:
    Code:
    Shape shape;
    means exactly the same as this code in c++:
    Code:
    Shape* shape;
    =================================================



    And when I was using polymorphism "feature" in Java, I wrote this:
    Code:
    Shape shape = new Circle();
    which in c++ code would look like this:
    Code:
    Shape* shape = new Circle;
    That's fine, all is great and I understand it.


    But there is another thing (what is not in Java): "references".
    I have read in various articles that I should prefer references before pointers (where it is possible) because it can improve efficiency and readability of the code (you can correct me if I am wrong).
    So I have used to references and now I use them where it is possible.

    But the problem is with polymorphism. If I want to use references also with polymorphism, I would write something like this:
    Code:
    Circle circle;
    Shape& shape = circle;
    But there another problem arises: "object slicing" (I don't want to explain this problem here, let's say that it is just a problem).


    And after this long message, here is my question:
    When I use polymorphism feature in c++, is it better to use pointers or references (or plain values) to achieve it (I think, the best thing would probably be to use pointers)?


    Thanks in advance.
    Petike

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Java's implementation is almost a cross between pointers and references, if this makes it easier to think about it. In C++, references can't be NULL, but in Java they can be null. In C++, the programmer can force a pointer to point to garbage (even if this isn't supposed to be allowed in many cases), but in Java, you can only explicitly set your reference to a valid object or to null.

    I wouldn't be worrying too badly about how to go about this. Use pointers in C++ where they make sense. Use references in C++ where they make sense.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    37
    Quote Originally Posted by Petike View Post
    I have read in various articles that I should prefer references before pointers (where it is possible) because it can improve efficiency and readability of the code (you can correct me if I am wrong).
    Well readability is a matter of opinion, but I will grant that it can sometimes improve readability. As for efficiency you have to know what you are doing. Blindly putting an & somewhere might not help you one bit. In a lot of cases references can save you some copying so it may improve efficiency, however in some of those cases pointers will do the same thing. It depends how you are using them and it also depends a lot on the compiler.

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Quote Originally Posted by Petike View Post
    When I use polymorphism feature in c++, is it better to use pointers or references (or plain values) to achieve it (I think, the best thing would probably be to use pointers)?
    .
    You have to use a pointer or reference to the base class to call a virtual function polymorphically. I usually store (smart) pointers to the base in containers, so I use pointers in that case. When passing to a function, I use references. Personal preference.

  5. #5
    Beginning game programmer Petike's Avatar
    Join Date
    Jan 2008
    Posts
    64

    Thumbs up Thanks

    Thanks for answers.
    So the best solution for me is probably what "medievalelks" said:
    "I usually store (smart) pointers to the base in containers, so I use pointers in that case. When passing to a function, I use references."
    Petike

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Petike
    So the best solution for me is probably what "medievalelks" said:
    "I usually store (smart) pointers to the base in containers, so I use pointers in that case. When passing to a function, I use references."
    Yes, but note that sometimes it makes sense to allow an argument to be "optional", in which case a (smart) pointer parameter would be more appropriate than a reference parameter so that a null pointer can be passed. (Of course, in terms of literally optional arguments, a default argument can still be provided for a const reference parameter.)
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Petike View Post
    But there another problem arises: "object slicing" (I don't want to explain this problem here, let's say that it is just a problem).
    Slicing only occurs if you try to store (or pass) a copy of a polymorphic type.
    If you store or pass the objects by reference or by pointer, no slicing will occur.
    So you can safely pass objects via reference without worry of slicing.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Beginning game programmer Petike's Avatar
    Join Date
    Jan 2008
    Posts
    64

    Question References: "no object slicing"?

    Quote Originally Posted by Elysia View Post
    Slicing only occurs if you try to store (or pass) a copy of a polymorphic type.
    If you store or pass the objects by reference or by pointer, no slicing will occur.
    So you can safely pass objects via reference without worry of slicing.
    Wow,
    so that is great, I thought that only in the case of "pointers" (as function arguments) the slicing doesn't occur.

    Thus, if I understand it well, when using the reference technique...
    Code:
    class Shape {};
    class Circle : public Shape {};
    
    // Function argument as reference...
    void polymorphicFunction(const Shape& shape)
    {
        /* Some code */
    }
    
    int main()
    {
        Circle circle;
        Shape& someShape = circle;
    
        // Pass the circle "as a shape" to the function
        polymorphicFunction(circle);
    }
    ...no object slicing will occur?


    Thanks.
    Petike

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    No slicing will occur.
    This will cause slicing:
    Code:
    class Shape {};
    class Circle : public Shape {};
    
    // Function argument as reference...
    void polymorphicFunction(Shape shape)
    {
        /* Some code */
    }
    
    int main()
    {
        Circle circle;
    
        // Pass the circle "as a shape" to the function
        polymorphicFunction(circle);
    }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Building on Elysia's example...

    Code:
    #include <iostream>
    
    using namespace std;
    
    class Shape {
    public:
        virtual ~Shape() {}
        virtual void doit() const { cout << "I'm a Shape" << endl; }
    };
    
    class Circle : public Shape {
    public:
        virtual void doit() const { cout << "I'm a Circle" << endl; }
    };
    
    void polymorphicFunctionPtr(const Shape * shape)
    {
        cout << "polymorphicFunctionPtr" << endl;
        shape->doit();
    }
    
    void polymorphicFunctionRef(const Shape & shape)
    {
        cout << "polymorphicFunctionRef" << endl;
        shape.doit();
    }
    
    void nonPolymorphicFunction(Shape shape)
    {
        cout << "nonPolymorphicFunction" << endl;
        shape.doit();
    }
    
    int main()
    {
        Circle circle;
    
        nonPolymorphicFunction(circle);
        polymorphicFunctionRef(circle);
        polymorphicFunctionPtr(&circle);
    }

  11. #11
    Beginning game programmer Petike's Avatar
    Join Date
    Jan 2008
    Posts
    64
    Once more many thanks for answers.
    Petike

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A C++ program examples showing Polymorphism, please help.
    By MarkSquall in forum C++ Programming
    Replies: 19
    Last Post: 06-06-2008, 04:41 AM
  2. Question on polymorphism
    By 6tr6tr in forum C++ Programming
    Replies: 3
    Last Post: 05-06-2008, 09:05 AM
  3. Replies: 3
    Last Post: 10-31-2005, 12:05 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