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

Thread: assignment operator for classes

  1. #1
    Join Date
    Mar 2009
    Posts
    58

    assignment operator for classes

    Getting a little confuse on this part.

    I give an example:

    Class A{
    char *str;
    int number;
    public:
    set(int);
    printnumber();
    };



    int main()
    {
    A b;
    int x =3;
    b.set(x);
    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*/
    e.printnumber();


    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.

    Thanks

  2. #2
    Join Date
    Nov 2008
    Location
    England
    Posts
    748

    Re: assignment operator for classes

    There is a difference between constructing a new object and assigning a new value to an existing object.
    Code:
    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
    Location
    San Diego, CA
    Posts
    1,054

    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 CodeGuru survey question.


Featured


HTML5 Development Center