Thread: Passing Objects, Constructors, Pointers, References, Values ???

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #14
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by Elysia View Post
    Code:
    class MyClass
    {
    public:
    	MyClass(const MyClass& rMyClass); // Copy constructor
    };
    
    int main()
    {
    	MyClass a;
    	MyClass b;
    	a = b; // Invokes copy constructor
    }
    Actually it doesn't. It'll invoke the assignment operator. That's why classes that overload the copy constructor should also overload the assignment operator.

    The copy constructor is called in any case where a copy of the class is needed, except the above.

    On the other hand, this does call the copy constructor:
    Code:
    class MyClass
    {
    public:
    	MyClass(const MyClass& rMyClass); // Copy constructor
    };
    
    int main()
    {
    	MyClass a;
    	MyClass b = a;// b is copy constructed from a.
            MyClass c(a); // alternate syntax for the above. Some say this is less ambiguous.
    }
    EDIT: laserlight beat me to it.
    Last edited by King Mir; 12-14-2007 at 02:47 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning an Array of Pointers to Objects
    By randomalias in forum C++ Programming
    Replies: 4
    Last Post: 04-29-2006, 02:45 PM
  2. Pointers to objects on the heap
    By foot in forum C++ Programming
    Replies: 3
    Last Post: 07-21-2005, 12:20 PM
  3. pointers in arrays... Declaring objects in a loop.
    By Guest852 in forum C++ Programming
    Replies: 10
    Last Post: 04-05-2005, 06:57 AM
  4. Pointers and references...
    By SushiFugu in forum C++ Programming
    Replies: 6
    Last Post: 12-08-2001, 04:21 PM
  5. Passing objects
    By Wiggin in forum C++ Programming
    Replies: 1
    Last Post: 10-17-2001, 08:00 AM