dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: define operator assignment

  1. #1
    Join Date
    May 2018
    Posts
    67

    define operator assignment

    With this following code:

    Code:
    void Display::alloca(){
      p = new bool*[N];
      for (int r=0; r<N; r++)
        p[r] = new bool[N];
    }
    
    void Display::dealloca(){
      for (int r=0; r<N; r++)
        delete [] p[r];
      delete [] p;
    }
    
    Display::Display(int N1){
      if ( N1<=0 || (N1%2)==0 )
        N = 5;
      else 
        N = N1;
      alloca();
      for (int r=0; r<N; r++){
        for (int c=0; c<N; c++)
          p[r][c] = false;
      }
    }
    
    Display & Display::operator =(const Display &d){
      if ( this != &d ){
        if ( N != d.N){
          dealloca();
          N = d.N;
          alloca();      
        }
        for (int r=0; r<N; r++)
          for (int c=0; c<N; c++)
            p[r][c] = d.p[r][c];
      }
      return *this;
    }

    partial main:

    Code:
    Display d2(5);
    Display d4(3);
    d4=d2;

    Can I define operator = in tis way? Where return value is void.
    I update class object and I give no return value. Perhaps standard operator = will give return class object and I can't change it?
    What do you think?

    Code:
    void Display::operator =(const Display &d){
      if ( this != &d ){
        if ( N != d.N){
          dealloca();
          N = d.N;
          alloca();      
        }
        for (int r=0; r<N; r++)
          for (int c=0; c<N; c++)
            p[r][c] = d.p[r][c];
      }
    
    }

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,750

    Re: define operator assignment

    Quote Originally Posted by zio_mangrovia
    Can I define operator = in tis way? Where return value is void.
    I update class object and I give no return value.
    Yes, you can.

    Quote Originally Posted by zio_mangrovia
    Perhaps standard operator = will give return class object and I can't change it?
    What do you think?
    The typical copy assignment operator would return the object itself by reference. This allows for operator chaining, which could be useful.

    Instead of implementing memory management yourself, have you considered using containers like std::vector instead? If that is somehow not an option, it is still more typical to implement the copy assignment operator using things like the copy/move constructor and a swap.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,460

    Re: define operator assignment

    When implementing a class that uses dynamic memory, as a minimum you need
    - constructor(s)
    - destructor
    - copy constructor (or marked as deleted)
    - copy assignment (or marked as deleted)

    and also since c++11 it is preferable to also have
    - move constructor
    - move assignment

    As some of these can be implemented easily using copy constructor, it is also advisable to also implement swap() as well. Copy assignment is then implemented in terms of copy constructor.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.8.7)

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,460

    Re: define operator assignment

    As you are preping for exams, consider

    Code:
    #include <algorithm>
    using namespace std;
    
    class Display
    {
    public:
    	// Default constructor
    	Display() {}
    
    	// Constructor array size
    	Display(int N1)
    	{
    		N = ((N1 <= 0) || (N1 % 2) == 0) ? 5 : N1;
    		alloca();
    		for (size_t r = 0; r < N; ++r)
    			for (size_t c = 0; c < N; ++c)
    				p[r][c] = false;
    	}
    
    	// Destructor
    	~Display()
    	{
    		dealloca();
    	}
    
    	// Copy constructor
    	Display(const Display& dis)
    	{
    		N = dis.N;
    		alloca();
    
    		for (size_t r = 0; r < N; ++r)
    			for (size_t c = 0; c < N; ++c)
    				p[r][c] = dis.p[r][c];
    	}
    
    	// Copy assignment
    	auto operator=(const Display& dis)
    	{
    		auto temp = dis;	// Calls copy constructor so temp is a copy of dis
    
    		swap(temp);		// Swaps pointers so class p now points to memory allocated to temp ie assignment has been done
    		return *this;		// Calls destructor for temp which now has pointer to old class p memory which is deallocated so no leakage
    	}
    
    	// Move constructor - dis is temporary and going to be destroyed
    	Display(Display&& dis)
    	{
    		swap(dis);
    	}
    
    	// Move assignment - dis is temporary and going to be destroyed
    	auto operator=(Display&& dis)
    	{
    		swap(dis);
    		return *this;
    	}
    
    private:
    	void alloca()
    	{
    		p = new bool*[N];
    		for (size_t r = 0; r < N; ++r)
    			p[r] = new bool[N];
    	}
    
    	void dealloca()
    	{
    		for (size_t r = 0; r < N; ++r)
    			delete[] p[r];
    
    		delete[] p;
    	}
    
    	void swap(Display& dis)
    	{
    		std::swap(dis.N, N);
    		std::swap(dis.p, p);
    	}
    
    	size_t N = 0;
    	bool ** p = nullptr;
    };
    Make sure you understand this. If you haven't covered move semantics yet, don't worry and just ignore this bit until you come to it.
    Last edited by 2kaud; May 26th, 2018 at 05:33 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.8.7)

  5. #5
    Join Date
    May 2018
    Posts
    67

    Re: define operator assignment

    OK, It's good explanation!
    So If I have exercise where I have to define class which uses dynamic memory and exercise doesn't request to create operator = (or equivalent, e.g. +=) or to define initialization (copy copy constructor), I need to mask both constructors so I can make sure code has no instructions to invoke these 2 constructors.
    Last edited by zio_mangrovia; June 8th, 2018 at 10:09 AM.

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,460

    Re: define operator assignment

    If a class uses dynamic memory then assume that all the constructors and destructor are required unless it says differently - then explicitly use =delete for those not required.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.8.7)

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




On-Demand Webinars (sponsored)