Operator overload

You should overload the operator+ such that you can perform the
following operation in the main function A = B + C; where A, B, and C
are all objects of type myarray and the values stored in A are given by
the values stored in B follwed by the values stored in C. Therefore A has
length equal to the sum of the length of B and the length of C.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  class MyArray {

private:
	int N;
	int* ptr;

public:
	// default constructor
	MyArray() {
		ptr = NULL;
		N = 0;
		
		// deletes the array pointed to by "ptr"
		// delete[] ptr;
	}
	// initialisation constructor
	MyArray(int n) {
		N = n;
		ptr = new int[N];	// dynamic memory allocation 
	}

	// destructor
	~MyArray() {
		delete[] ptr; // memory is released
	}

	// member functions
	int getVal(int i) {
		if (i < N)
			return ptr[i];
		else
			cout << "Error!";
	}
	
	
	void setVal(int i, int val) {
		if (i < N)
			ptr[i] = val;
		else
			cout << "Error!";
	}
	// print function for debugging
	void print(int i) {
		cout << ptr[i];
	}


This is what i have so far, but not sure how to overload it.
- Do I need to create a member function that adds two objects and then overload '+' outside the class?
Any help? Thanks
Last edited on
You are on the right track. The recommended member function is operator+=.

See "Binary arithmetic" in http://en.cppreference.com/w/cpp/language/operators


Note: See Rule of Three in http://en.cppreference.com/w/cpp/language/rule_of_three
In other words: you do need custom copy constructor and copy assigment.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
using namespace std;

class MyArray {

private:
	int N;
	int* ptr;

public:
	// default constructor
	MyArray() {
		ptr = NULL;
		N = 0;
		
		// deletes the array pointed to by "ptr"
		// delete[] ptr;
	}
	// initialisation constructor
	MyArray(int n) {
		N = n;
		ptr = new int[N];	// dynamic memory allocation 

		// set values to zero / debugging
		for (int i = 0; i < N; i++) {
			ptr[i] = 0;
		}
	}

	// destructor
	~MyArray() {
		delete[] ptr; // memory is released
	}

	// member functions6
	int getVal(int i) {
		if (i < N)
			return ptr[i];
		else
			cout << "Error!";
	}
	
	// two parameters to the function***
	void setVal(int i, int val) {
		if (i < N)
			ptr[i] = val;
		else
			cout << "Error!";
	}
	// print function for debugging
	void print(int i) {
		cout << ptr[i];
	}

	void push() {
		cout << endl << (sizeof(ptr) / sizeof(*ptr));
	}

	MyArray operator+(const MyArray&) const;       // operator+()

};

// define overloaded + (plus) operator
MyArray MyArray::operator+ (const MyArray& obj) const
{
      MyArray operator+(const MyArray&);    
	  MyArray result;
	  result.N = (this->N + obj.N);
      return result;
}

int main() {

	MyArray test1(8);
	MyArray test2(2);

	MyArray test = test1 + test2;
	test.print(1);
	cin.get();
}


I wrote it like this.. however i am getting an error once i try to either print or get value from a new object. I am finding this fairly difficult. I appreciate your help!
Last edited on
Has anyone got a solution to this yet? The closest I have come is this....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
using namespace std;

class MyArray {

private:
	int N;
	int* ptr;

public:
	// default constructor
	MyArray() {
		ptr = NULL;
		N = 0;

		// deletes the array pointed to by "ptr"
		// delete[] ptr;
	}

	// initialisation constructor
	MyArray(int n) {
		N = n;
		ptr = new int[N];	// dynamic memory allocation 

							// set values to zero / debugging
		for (int i = 0; i < N; i++) {
			ptr[i] = 0;
		}
	}

	// destructor
	~MyArray() {
		delete[] ptr; // memory is released
	}

	// member functions6
	int getVal(int i) {
		if (i < N)
			return ptr[i];
		else
			cout << "Error!";
	}

	// two parameters to the function***
	void setVal(int i, int val) {
		if (i < N)
			ptr[i] = val;
		else
			cout << "Error!";
	}

	// print function for debugging
	void print(int i) {
		cout << ptr[i];
	}

	void push() {
		cout << endl << (sizeof(ptr) / sizeof(*ptr));
	}

	MyArray operator+(const MyArray&) const;       // operator+()

};

// define overloaded + (plus) operator
MyArray MyArray::operator+ (const MyArray& obj) const
{
	//MyArray operator+(const MyArray&);
	MyArray result(N + obj.N);

	return result;
}

int main() {

	MyArray test1(8);
	MyArray test2(2);

	MyArray test = test1 + test2;
	test.print(1);
	cin.get();
}


I think the problem is the destructor. It deletes the pointer before it can be assigned to the new object. Also creating MyArray test, would this not first call the default constructor? That creates its own problems...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <memory>
#include <initializer_list>
#include <algorithm>
#include <iterator>

struct my_array
{
    my_array() = default ;

    explicit my_array( std::size_t n ) : sz(n), ptr( new int[n]{} ) {}

    // http://en.cppreference.com/w/cpp/utility/initializer_list
    // http://en.cppreference.com/w/cpp/algorithm/copy
    my_array( std::initializer_list<int> ilist ) : my_array( ilist.size() ) // for testing
    { std::copy( ilist.begin(), ilist.end(), ptr ) ; }

    my_array( const my_array& that ) : my_array( that.sz )
    { std::copy_n( that.ptr, sz, ptr ) ; } // http://en.cppreference.com/w/cpp/algorithm/copy_n

    my_array( my_array&& that ) noexcept { swap(that) ; }

    // copy-and-swap assignment operator (aka unifying assignment operator)
    // see: Canonical implementations: assignment operators
    // http://en.cppreference.com/w/cpp/language/operators
    my_array& operator= ( my_array that ) noexcept { swap(that) ; return *this ; }

    ~my_array() { delete[] ptr ; }

    void swap( my_array& that ) noexcept // http://en.cppreference.com/w/cpp/algorithm/swap
    { using std::swap ; swap(sz,that.sz) ; swap(ptr,that.ptr) ; }

    my_array& operator+= ( const my_array& that )
    {
        if( that.sz )
        {
            my_array temp( sz + that.sz ) ;
            std::copy_n( ptr, sz, temp.ptr ) ;
            std::copy_n( that.ptr, that.sz, temp.ptr+sz ) ;
            swap(temp) ;
        }

        return *this ;
    }

    private:
        std::size_t sz = 0 ;
        int* ptr = nullptr ; // raw owning ptr:

    // see: Canonical implementations: Binary arithmetic operators
    // http://en.cppreference.com/w/cpp/language/operators
    friend my_array operator+ ( my_array first, const my_array& second )
    { return first += second ; }

    // see: Canonical implementations: Stream extraction and insertion
    // http://en.cppreference.com/w/cpp/language/operators
    friend std::ostream& operator<< ( std::ostream& stm, const my_array& arr )
    {
        stm << "[ " ;
        std::copy( arr.ptr, arr.ptr+arr.sz, std::ostream_iterator<int>( stm, " " ) ) ;
        return stm << ']' ;
    }
};

void swap( my_array& a, my_array& b ) noexcept { a.swap(b) ; }

int main()
{
    const my_array a { 10, 11, 12, 13, 14, 15 } ;
    const my_array b { 56, 57, 58, 59, 60, 61, 62, 63, 64 } ;
    
    std::cout << a << " + " << b << " == " << a+b << '\n' ;
    const my_array c = a+b ;
    std::cout << c << '\n' ;

    my_array d ;
    std::cout << b << " + " << a << " == " << b+a << '\n' ;
    d = b + a ;
    std::cout << d << '\n' ;
}

http://coliru.stacked-crooked.com/a/b85f581b62d09ab3
That is some fancy code. I bet I could learn a lot from it. Unfortunately it does not build on my computer. I get this error...

invalid specifier outside a class declaration


It does not like line 52.
Which compiler (version) and which C++ version do you use?
> invalid specifier outside a class declaration
> It does not like line 52.

Make sure that you have not terminated the class definition with a spurious }; before line 52.
I use VS2015. This is not even my original post. I saw it and liked the challenge, and it has been kicking my butt ever since. *Laughs*

And I could probably do this a lot easier with vectors but the post said arrays.
ok, so here is my next question. If I create a smart pointer. That is to say, a pointer wrapped in a class that deletes itself upon dropping out of scope, and then build my array out of those, do I still have to delete the array or will it take care of itself since the smart pointers delete them selves?
You can test that.

Your array does currently store ints. Replace that with MyInt.

1
2
3
4
5
struct MyInt {
  ~MyInt() {
    std::cout << "They did kill Kenny!\n";
  }
};

These boys will cry, if you do your deletion right.
Topic archived. No new replies allowed.