Related to this question that I asked yesterday.
I'm building my own vector class to learn a little more about C++, and I'm having some difficulty implementing an overloaded operator+
that I can use to add vectors. Here's what my class looks like so far:
template<typename T>
class vector;
template<typename T>
vector<T> operator+(const vector<T>&, const vector<T>&);
template<typename T>
class vector
{
private:
T* pointer_;
unsigned long size_;
public:
// Constructors and destructors.
vector();
template<typename A> vector(const A&);
template<typename A> vector(const A&, const T&);
vector(const vector<T>&);
~vector();
// Methods.
unsigned long size();
T* begin();
T* end();
vector<T>& push_back(const T&);
// Operators.
T operator[](unsigned long);
vector<T>& operator=(const vector<T>&);
friend vector<T> operator+<>(const vector<T>&, const vector<T>&);
};
template<typename T>
vector<T> operator+(const vector<T>& lhs, const vector<T>& rhs)
{
vector<T> result(lhs.size_);
for (unsigned long i = 0; i != result.size_; i++)
{
result.pointer_[i] = lhs.pointer_[i] + rhs.pointer_[i];
}
return result;
}
The constructor vector(const A& size, const T& value)
operates as expected, returning a vector with size
elements initialized to value
. operator=
appears to be working, as well. When I try something like this, however, my program doesn't perform as expected:
#include <iostream>
#include "vector.h"
int main()
{
vector<int> test(5, 2); // Create a vector with five elements initialized to 2.
vector<int> test2(5, 3); // Create a vector with five elements initialized to 3.
std::cout << test.size() // Prints 5, as expected.
std::cout << test2.size() // Prints 5, as expected.
vector<int> try_result = test + test2;
std::cout << try_result.size() // Prints 0--why?
}
My question: if operator+
returns a copy of result
(and not by reference, a problem that originally existed in my code), why does it appear that try_result
still does not point to the proper location in the heap?
EDIT: Adding the constructor code (I've tested this, and it seems to work, but maybe for the wrong reasons):
template<typename T> template<typename A>
vector<T>::vector(const A& size)
{
this->pointer_ = new T[size];
this->size_ = size;
}
template<typename T> template<typename A>
vector<T>::vector(const A& size, const T& initial_value)
{
this->pointer_ = new T[size];
this->size_ = size;
for (unsigned long i = 0; i != this->size_; i++)
{
pointer_[i] = initial_value;
}
}
EDIT2: Adding the copy constructor.
template<typename T>
vector<T>::vector(const vector<T>& replicate_vector)
{
delete[] this->pointer_;
this->pointer_ = new T[replicate_vector.size_];
this->size_ = replicate_vector.size_;
for (unsigned long i = 0; i != this->size_; i++)
{
this->pointer_[i] = replicate_vector.pointer_[i];
}
}