assignment operator for classes
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 3 of 3

Thread: assignment operator for classes

  1. #1
    Join Date
    Mar 2009

    assignment operator for classes

    Getting a little confuse on this part.

    I give an example:

    Class A{
    char *str;
    int number;

    int main()
    A b;
    int x =3;
    A c(&b) /*this calls copy constructor which is grand
    A d = c /*this calls copy consturctor which is grand

    A e;
    e=b; /*doesnt call copy constructor*/

    My question is what does the assignment operator do? Does it just copy the values across from B?
    HOw is it different to the copy constructor?
    Why do we need to overload the assignment operator if we overload the copy constructor?
    I know it will print the value 3 out.


  2. #2
    Join Date
    Nov 2008

    Re: assignment operator for classes

    There is a difference between constructing a new object and assigning a new value to an existing object.
    class A {};
    void func()
       A first; // calls default constructor to make a new A called first.
       A copy_of_first( first ); // calls copy constructor to construct a new A thats a direct copy of first.
       A second;
       first = second; // this is assignment. We dont create first, we just give it a new value
       A third = second; // this is initialisation. Its a copy constructor call.
    I hope that clears things up a bit.
    Get Microsoft Visual C++ Express here or CodeBlocks here.
    Get STLFilt here to radically improve error messages when using the STL.
    Get these two can't live without C++ libraries, BOOST here and Loki here.
    Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
    Always use [code] code tags [/code] to make code legible and preserve indentation.
    Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.

  3. #3
    Join Date
    Aug 2005
    San Diego, CA

    Re: assignment operator for classes

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

This is a survey!

HTML5 Development Center