Thread: containers/ assignment operator

  1. #1
    Registered User Kirdra's Avatar
    Join Date
    Aug 2002
    Posts
    105

    containers/ assignment operator

    My docs on the vector class says it's compatible with classes that have copy contructers and assignment operators, how would I define these operaters, I think I know how to do the copy constructer but not the assignment one...

    Something to do with not mixing the pointers up, I know. Just not familar with operator overloading. thx.

  2. #2
    Registered User
    Join Date
    Oct 2004
    Posts
    120
    Both methods are similar. A copy constructor is a construtor that takes a reference to a class of the same type and simply copies the data from the argument to the local class. Most compilers will do a memberwise copy by default, but this is bad if you use anything but the basic types (int, char...)

    An assignment operator does the same thing, only its done on a class that has already been constructed.

    Code:
    class myClass {
    public:
      int data;
    
      myClass() : data(0) {}
      myClass(myClass &copy) {data = copy.data;}
    
      myClass& operator=(myClass &rhs) {data = rhs.data; return *this;}
    };
    Its a simple example, but I hope it helps.

    PK

  3. #3
    Registered User Kirdra's Avatar
    Join Date
    Aug 2002
    Posts
    105
    That's great.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Crazy Assignment Operator Semantics
    By SevenThunders in forum C++ Programming
    Replies: 7
    Last Post: 01-22-2009, 01:08 PM
  2. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  3. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  4. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM