Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. How to write copy constructor when returning any template object.

How to write copy constructor when returning any template object.

Scheduled Pinned Locked Moved C / C++ / MFC
helptutorial
19 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Atul23
    wrote on last edited by
    #1

    Hi ALL, I am writing function which return template object of type CArray. Following is the defintion for this. CArray COpenFolderPage::GetPagesPath() { CArray pagePathArray; // some code return pagePathArray; } When i compile this code, then there is error as "no copy constructor is found" So how to write copy constructor in this case. Thanks in Advance Atul

    N C C J 4 Replies Last reply
    0
    • A Atul23

      Hi ALL, I am writing function which return template object of type CArray. Following is the defintion for this. CArray COpenFolderPage::GetPagesPath() { CArray pagePathArray; // some code return pagePathArray; } When i compile this code, then there is error as "no copy constructor is found" So how to write copy constructor in this case. Thanks in Advance Atul

      N Offline
      N Offline
      Nelek
      wrote on last edited by
      #2

      I made a lot of different objects in my project deriving from CObject. In all of them I have the constructor/destructor, copy and assingment operators, and in just some the equality operator

      //header.h
      CMyObject();
      CMyObject(const CMyObject &obj); // Copy operator
      CMyObject& operator= (const CMyObject &obj); // Assigment Operator
      BOOL operator== (const CMyObject &obj); // Equalty operator
      virtual ~CMyObject();

      and I code them following this schema

      CMyObject::CMyObject()
      { m_dVar1 = 0.0;
      m_bVar2 = FALSE;
      //and so on
      }

      //***********

      CMyObject::CMyObject(const CMyObject &obj)
      { m_dVar1 = obj.m_dVar1;
      m_bVar2 = obj.m_bVar2;
      // and one more for every member variable that the class owns
      }

      //***********

      CMyObject& CMyObject::operator= (const CMyObject &obj)
      { m_bVar1 = obj.m_bVar1;
      m_bVar2 = obj.m_bVar2;
      // and one more for every member variable that the class owns
      return *this;
      }

      //***********

      BOOL CMyObject::operator== (const CMyObject &obj)
      { return ((this->m_bVar1 == obj.m_bVar1) &&
      (this->m_bVar2 == obj.m_bVar2) &&
      // and one more for every member variable that the class owns
      );
      }

      //***********

      CMyObject::~CMyObject()
      {
      //if the object has lists or arrays, delete the contents...
      //free possible used memory...
      }

      With this schema you can use the object in arrays, in lists, just as independant object and make operations and so on. Up to complicated hierachies of objects that are owned from other objects. (For more info about what I mean take a look into my answers in the comments of my article SmartListII[^], I wrote there more or less the structure I use with the objects in one project, using lists, arrays and so on)

      Greetings. -------- M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you “The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet.” - Michael A. Jackson

      1 Reply Last reply
      0
      • A Atul23

        Hi ALL, I am writing function which return template object of type CArray. Following is the defintion for this. CArray COpenFolderPage::GetPagesPath() { CArray pagePathArray; // some code return pagePathArray; } When i compile this code, then there is error as "no copy constructor is found" So how to write copy constructor in this case. Thanks in Advance Atul

        C Offline
        C Offline
        codeII
        wrote on last edited by
        #3

        pagePathArray( pagePathArray& rhs )
        {
        m_memberOne = rhs.m_memberOne;
        ...
        }

        Or easier:

        void COpenFolderPage::GetPagesPath( CArray<type,type>& pagePathArray )
        {
        }

        1 Reply Last reply
        0
        • A Atul23

          Hi ALL, I am writing function which return template object of type CArray. Following is the defintion for this. CArray COpenFolderPage::GetPagesPath() { CArray pagePathArray; // some code return pagePathArray; } When i compile this code, then there is error as "no copy constructor is found" So how to write copy constructor in this case. Thanks in Advance Atul

          C Offline
          C Offline
          CPallini
          wrote on last edited by
          #4

          Do you want to do exactly what your code implies? Sure? Do you want to return a copy of the local CArray object? Uhm...:confused: :)

          If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

          1 Reply Last reply
          0
          • A Atul23

            Hi ALL, I am writing function which return template object of type CArray. Following is the defintion for this. CArray COpenFolderPage::GetPagesPath() { CArray pagePathArray; // some code return pagePathArray; } When i compile this code, then there is error as "no copy constructor is found" So how to write copy constructor in this case. Thanks in Advance Atul

            J Offline
            J Offline
            jhwurmbach
            wrote on last edited by
            #5

            Because the board software eats all > and <.

            CArray<type, type> COpenFolderPage::GetPagesPath()
            {

            CArray<type, type> pagePathArray;

            // some code

            return pagePathArray;
            }

            looks quite reasonable. CArray surly has a copy-c'tor. Otherwise the class is much more broken than I ever imagined. Hint: std::vector<type> works equally well and is actually modern C++ instead of some funny hack for MS C++ 4 (of 10 years ago). -- modified at 4:56 Monday 19th November, 2007 Major oops - nevermind. If you saw the interim-version: Forget it immediatly!


            Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
            Douglas Adams, "Dirk Gently's Holistic Detective Agency"

            C D 2 Replies Last reply
            0
            • J jhwurmbach

              Because the board software eats all > and <.

              CArray<type, type> COpenFolderPage::GetPagesPath()
              {

              CArray<type, type> pagePathArray;

              // some code

              return pagePathArray;
              }

              looks quite reasonable. CArray surly has a copy-c'tor. Otherwise the class is much more broken than I ever imagined. Hint: std::vector<type> works equally well and is actually modern C++ instead of some funny hack for MS C++ 4 (of 10 years ago). -- modified at 4:56 Monday 19th November, 2007 Major oops - nevermind. If you saw the interim-version: Forget it immediatly!


              Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
              Douglas Adams, "Dirk Gently's Holistic Detective Agency"

              C Offline
              C Offline
              CPallini
              wrote on last edited by
              #6

              Much better, but I still think it is not a good idea to return a copy of the local array. :)

              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

              J 1 Reply Last reply
              0
              • J jhwurmbach

                Because the board software eats all > and <.

                CArray<type, type> COpenFolderPage::GetPagesPath()
                {

                CArray<type, type> pagePathArray;

                // some code

                return pagePathArray;
                }

                looks quite reasonable. CArray surly has a copy-c'tor. Otherwise the class is much more broken than I ever imagined. Hint: std::vector<type> works equally well and is actually modern C++ instead of some funny hack for MS C++ 4 (of 10 years ago). -- modified at 4:56 Monday 19th November, 2007 Major oops - nevermind. If you saw the interim-version: Forget it immediatly!


                Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                D Offline
                D Offline
                David Crow
                wrote on last edited by
                #7

                jhwurmbach wrote:

                Because the board software eats all >...

                Only if it first finds a < character.


                "Normal is getting dressed in clothes that you buy for work and driving through traffic in a car that you are still paying for, in order to get to the job you need to pay for the clothes and the car and the house you leave vacant all day so you can afford to live in it." - Ellen Goodman

                "To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne

                J 1 Reply Last reply
                0
                • C CPallini

                  Much better, but I still think it is not a good idea to return a copy of the local array. :)

                  If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                  J Offline
                  J Offline
                  jhwurmbach
                  wrote on last edited by
                  #8

                  As long as he does not return a pointer or reference to it, I think there is nothing wrong.


                  Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                  Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                  C 1 Reply Last reply
                  0
                  • D David Crow

                    jhwurmbach wrote:

                    Because the board software eats all >...

                    Only if it first finds a < character.


                    "Normal is getting dressed in clothes that you buy for work and driving through traffic in a car that you are still paying for, in order to get to the job you need to pay for the clothes and the car and the house you leave vacant all day so you can afford to live in it." - Ellen Goodman

                    "To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne

                    J Offline
                    J Offline
                    jhwurmbach
                    wrote on last edited by
                    #9

                    OK, I might have used the wrong word: What are < > called, then? In German, < ( [ and { are all called "Klammer", with the possible distinction as "spitz" (pointed), "rund" (rounded), "eckig" (squared) and "geschweift" (cambered?) when needed.


                    Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                    Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                    D 1 Reply Last reply
                    0
                    • J jhwurmbach

                      As long as he does not return a pointer or reference to it, I think there is nothing wrong.


                      Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                      Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                      C Offline
                      C Offline
                      CPallini
                      wrote on last edited by
                      #10

                      As you are pointing out, it is not an error; anyway, as I pointed out, it is not a good idea (hint: efficiency). :)

                      If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                      J 1 Reply Last reply
                      0
                      • C CPallini

                        As you are pointing out, it is not an error; anyway, as I pointed out, it is not a good idea (hint: efficiency). :)

                        If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                        J Offline
                        J Offline
                        jhwurmbach
                        wrote on last edited by
                        #11

                        That is probably premature optimisation. When specifically this copying of the array slows the whole application down, then we can think about how we speed his code up. :-D


                        Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                        Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                        C 1 Reply Last reply
                        0
                        • J jhwurmbach

                          That is probably premature optimisation. When specifically this copying of the array slows the whole application down, then we can think about how we speed his code up. :-D


                          Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                          Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                          C Offline
                          C Offline
                          CPallini
                          wrote on last edited by
                          #12

                          Oh no, this is definitely NOT premature optimization. The original method design is simply bad: whenever you deal with array or (not trivial) objects, reference passing is a must (unless you have strong motivations to do the opposite). Premature optimization is bad. Bad design is even worse. :-D

                          If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                          J 1 Reply Last reply
                          0
                          • C CPallini

                            Oh no, this is definitely NOT premature optimization. The original method design is simply bad: whenever you deal with array or (not trivial) objects, reference passing is a must (unless you have strong motivations to do the opposite). Premature optimization is bad. Bad design is even worse. :-D

                            If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                            J Offline
                            J Offline
                            jhwurmbach
                            wrote on last edited by
                            #13

                            OK, you won. I am changing my function definition to

                            const CArray& COpenFolderPage::GetPagesPath()

                            Oh- wait! The Array is a function-local variable. We *have to* return it by value! The compiler would have to do a copy anyway. We have three objects involved: TargetArray - temporary - Source( local to function) The target being a mere reference is illegal, because the local variable goes out of scope. So, in all possible implementations, two of the three objects can be merged in one by the optimizer, but never all three. The compiler has to copy once. -- modified at 4:58 Monday 19th November, 2007 (This modification overlapped with the replyh


                            Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                            Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                            C 2 Replies Last reply
                            0
                            • J jhwurmbach

                              OK, you won. I am changing my function definition to

                              const CArray& COpenFolderPage::GetPagesPath()

                              Oh- wait! The Array is a function-local variable. We *have to* return it by value! The compiler would have to do a copy anyway. We have three objects involved: TargetArray - temporary - Source( local to function) The target being a mere reference is illegal, because the local variable goes out of scope. So, in all possible implementations, two of the three objects can be merged in one by the optimizer, but never all three. The compiler has to copy once. -- modified at 4:58 Monday 19th November, 2007 (This modification overlapped with the replyh


                              Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                              Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                              C Offline
                              C Offline
                              CPallini
                              wrote on last edited by
                              #14

                              Because the local variable goes out of scope. :-D I know, I'm quite polemical, cheers :rose:

                              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                              J 1 Reply Last reply
                              0
                              • C CPallini

                                Because the local variable goes out of scope. :-D I know, I'm quite polemical, cheers :rose:

                                If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                                J Offline
                                J Offline
                                jhwurmbach
                                wrote on last edited by
                                #15

                                CPallini wrote:

                                I know, I'm quite polemical, cheers

                                No you are'nt. I was acting faster than I was thinking. But I was just in the processinng of modifying my post... :-D


                                Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                                Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                                1 Reply Last reply
                                0
                                • J jhwurmbach

                                  OK, you won. I am changing my function definition to

                                  const CArray& COpenFolderPage::GetPagesPath()

                                  Oh- wait! The Array is a function-local variable. We *have to* return it by value! The compiler would have to do a copy anyway. We have three objects involved: TargetArray - temporary - Source( local to function) The target being a mere reference is illegal, because the local variable goes out of scope. So, in all possible implementations, two of the three objects can be merged in one by the optimizer, but never all three. The compiler has to copy once. -- modified at 4:58 Monday 19th November, 2007 (This modification overlapped with the replyh


                                  Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                                  Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                                  C Offline
                                  C Offline
                                  CPallini
                                  wrote on last edited by
                                  #16

                                  What about

                                  bool COpenFolderPage::GetPagesPath(CArray < type, type > & pagePathArray )
                                  {
                                  bool success;

                                  // some code using pagePathArray

                                  return success;
                                  }

                                  ? :-D

                                  If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                                  J 1 Reply Last reply
                                  0
                                  • C CPallini

                                    What about

                                    bool COpenFolderPage::GetPagesPath(CArray < type, type > & pagePathArray )
                                    {
                                    bool success;

                                    // some code using pagePathArray

                                    return success;
                                    }

                                    ? :-D

                                    If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                                    J Offline
                                    J Offline
                                    jhwurmbach
                                    wrote on last edited by
                                    #17

                                    Better. Not as expressive, though. Plus it might or might not be faster. E.g. the function could need a very large temporary array in its algorithm. This would then enlarge the callers array, without shrinking it, like a copy would do. Also, it is not as easy to not touch the callers array in case of the call not succeding.


                                    Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                                    Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                                    C 1 Reply Last reply
                                    0
                                    • J jhwurmbach

                                      Better. Not as expressive, though. Plus it might or might not be faster. E.g. the function could need a very large temporary array in its algorithm. This would then enlarge the callers array, without shrinking it, like a copy would do. Also, it is not as easy to not touch the callers array in case of the call not succeding.


                                      Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                                      Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                                      C Offline
                                      C Offline
                                      CPallini
                                      wrote on last edited by
                                      #18

                                      jhwurmbach wrote:

                                      E.g. the function could need a very large temporary array in its algorithm. This would then enlarge the callers array, without shrinking it, like a copy would do.

                                      You can address all the above requirements inside method definition without loss of efficiency (e.g. if you need a temporary array then explicitely instantiate it, no need to pollute caller array). The code snippet shows how to remove an unnecessary copy step. If it is a big advantage or not depends on method logic, of course. :)

                                      If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                                      1 Reply Last reply
                                      0
                                      • J jhwurmbach

                                        OK, I might have used the wrong word: What are < > called, then? In German, < ( [ and { are all called "Klammer", with the possible distinction as "spitz" (pointed), "rund" (rounded), "eckig" (squared) and "geschweift" (cambered?) when needed.


                                        Let's think the unthinkable, let's do the undoable, let's prepare to grapple with the ineffable itself, and see if we may not eff it after all.
                                        Douglas Adams, "Dirk Gently's Holistic Detective Agency"

                                        D Offline
                                        D Offline
                                        David Crow
                                        wrote on last edited by
                                        #19

                                        jhwurmbach wrote:

                                        OK, I might have used the wrong word...

                                        No, I was just saying that replacing both of them was not necessary. Simply replacing the left bracket is all that's necessary.

                                        jhwurmbach wrote:

                                        What are < > called, then?

                                        Angle brackets.


                                        "Normal is getting dressed in clothes that you buy for work and driving through traffic in a car that you are still paying for, in order to get to the job you need to pay for the clothes and the car and the house you leave vacant all day so you can afford to live in it." - Ellen Goodman

                                        "To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne

                                        1 Reply Last reply
                                        0
                                        Reply
                                        • Reply as topic
                                        Log in to reply
                                        • Oldest to Newest
                                        • Newest to Oldest
                                        • Most Votes


                                        • Login

                                        • Don't have an account? Register

                                        • Login or register to search.
                                        • First post
                                          Last post
                                        0
                                        • Categories
                                        • Recent
                                        • Tags
                                        • Popular
                                        • World
                                        • Users
                                        • Groups