473,395 Members | 1,623 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Operator () overloading, cannot return by value.

Hi All,

Im a newbie to C++, I am trying to customize the vector template
STL to a template Class. My code is shown below. Im confused about
something and maybe somebody here might be able to help me.

Lets say X is my vector, which contains 10 elements. I want to
assign elements indexed 2 to 5 to another vector Y, so I want to do it
like Y = X(2,5). So what I do is i overload the () operators, as
marked in (a) below. This creates a new intermidate Vector class Z,
via the constructor that is marked (b) below. The intermediate vector
class is returned to (a), which thens try to return by value. However
my memory always gets destroyed. This makes sense because I created a
variable which has scope only in (a).

However, when I add to vectors X + Y, again an intermediate result
is created. This is done in (c) below. The X (lhs) argument is used to
call another constructor which then creates a copy Z, and adds Y (rhs)
to that copy Z. Now Z is then returned but it does not get destroyed.

So to sum up, why does memory gets destroyed in the first case but
not in the second. And how to avoid this problem in the first case?

Thanks in advance.

/*------------------------------------------------
This is package for Vectors, Matrices (Template Class)
--------------------------------------------------*/
#include <iostream>
#include <vector>
#include <math.h>
#define to ,
using namespace std;

//********************** START: VECTOR *************************
template <typename TYPE>
class Vector {
vector<TYPEv;
public:
//************************************************** ******
// Selectors
const TYPE& operator[](const int& k) const { return v[k]; } //default
[] indexing
const TYPE& operator()(const int& k) const {return v[k];}
int size() const {return v.size();} //returns the size

const Vector<TYPEoperator()(const int& i,const int& j) <---- (a)
return Vector<TYPE>(v, i, j);

//************************************************** ******
// Constructors and Destructor
Vector() { };
~Vector(){ };

//************************************************** ******
//plus operation
Vector<TYPE>& operator+=(const Vector<TYPE>& rhs){
for (int k = 0; k < rhs.size(); k++){
if (k < v.size())
v[k] += rhs[k];
else v.push_back(rhs[k]);
}
return *this;
}

//************************************************** ******
// Copiers
//copy constructors
Vector( const Vector<TYPE>& val) { //copy constructor for
intermediate results (like x + y)
for (int k = 0; k < val.size(); k++)
v.push_back(val[k]);
}
Vector( const Vector<TYPE>& val, const int& i, const int& j)
{ <----- (b)
//this constructor is used to create copy when indexing a range
for (int k = i; k <=j; k++){
if (k<val.size())
v.push_back(val[k]);
else v.push_back(0);
}
}

//assignments
Vector<TYPE>& operator=(const Vector<TYPE>& rhs) {
v.clear();
for (int k = 0; k < rhs.size(); k++)
v.push_back(rhs[k]);
return *this;
}
};

//************************************************** ******
//plus operation
template <typename TYPE>
inline const Vector<TYPEoperator+(const Vector<TYPE>& lhs, const
Vector<TYPE>& rhs)
{
return Vector<TYPE>(lhs) += rhs; <----- (c)
}
//********************** END: VECTOR *************************
Sep 8 '08 #1
4 1976
Hi fabian.
May be difference in this:

const Vector<TYPE operator()(const int& i,const int& j) <---- (a)
{...}
Vector<TYPE>& operator+=(const Vector<TYPE>& rhs){...}

Should you use:

const Vector<TYPE>& operator()(const int& i,const int& j) <---- (a)
{...}

instead

const Vector<TYPE operator()(const int& i,const int& j) <---- (a)
{...}
Sep 8 '08 #2
On 8 Sep, 08:53, fabian....@gmail.com wrote:
Hi All,

* *Im a newbie to C++, I am trying to customize the vector template
STL to a template Class. My code is shown below. Im confused about
something and maybe somebody here might be able to help me.

* *Lets say X is my vector, which contains 10 elements. I want to
assign elements indexed 2 to 5 to another vector Y, so I want to do it
like Y = X(2,5). So what I do is i overload the () operators, as
marked in (a) below. This creates a new intermidate Vector class Z,
via the constructor that is marked (b) below. The intermediate vector
class is returned to (a), which thens try to return by value. However
my memory always gets destroyed. This makes sense because I created a
variable which has scope only in (a).

* *However, when I add to vectors X + Y, again an intermediate result
is created. This is done in (c) below. The X (lhs) argument is used to
call another constructor which then creates a copy Z, and adds Y (rhs)
to that copy Z. Now Z is then returned but it does not get destroyed.

* *So to sum up, why does memory gets destroyed in the first case but
not in the second. And how to avoid this problem in the first case?

Thanks in advance.

/*------------------------------------------------
This is package for Vectors, Matrices (Template Class)
--------------------------------------------------*/
#include <iostream>
#include <vector>
#include <math.h>
#define to ,
using namespace std;

//********************** START: VECTOR *************************
template <typename TYPE>
class Vector {
* * * * vector<TYPEv;
public:
* * * * //************************************************** ******
* * * * // * *Selectors
* * * * const TYPE& operator[](const int& k) const { return v[k];} //default
[] indexing
* * * * const TYPE& operator()(const int& k) const {return v[k];}
* * * * int size() const {return v.size();} //returns the size

* * * * const Vector<TYPEoperator()(const int& i,const int& j) <---- (a)
* * * * * * * * return Vector<TYPE>(v, i, j);

* * * * //************************************************** ******
* * * * // * *Constructors and Destructor
* * * * Vector() { };
* * * * ~Vector(){ };

* * * * //************************************************** ******
* * * * //plus operation
* * * * Vector<TYPE>& operator+=(const Vector<TYPE>& rhs){
* * * * * * * * for (int k = 0; k < rhs.size(); k++){
* * * * * * * * * * * * if (k < v.size())
* * * * * * * * * * * * * * * * v[k] +=rhs[k];
* * * * * * * * * * * * else v.push_back(rhs[k]);
* * * * * * * * }
* * * * * * * * return *this;
* * * * }

* * * * //************************************************** ******
* * * * // * *Copiers
* * * * //copy constructors
* * * * Vector( const Vector<TYPE>& val) { //copy constructor for
intermediate results (like x + y)
* * * * * * * * for (int k = 0; k < val.size(); k++)
* * * * * * * * * * * * v.push_back(val[k]);
* * * * }
* * * * Vector( const Vector<TYPE>& val, const int& i, const int&j)
{ * *<----- (b)
* * * * * * * * //this constructor is used to create copywhen indexing a range
* * * * * * * * for (int k = i; k <=j; k++){
* * * * * * * * * * * * if (k<val.size())
* * * * * * * * * * * * * * * * v.push_back(val[k]);
* * * * * * * * * * * * else v.push_back(0);
* * * * * * * * }
* * * * }

* * * * //assignments
* * * * Vector<TYPE>& operator=(const Vector<TYPE>& rhs) {
* * * * * * * * v.clear();
* * * * * * * * for (int k = 0; k < rhs.size(); k++)
* * * * * * * * * * * * v.push_back(rhs[k]);
* * * * * * * * return *this;
* * * * }

};

//************************************************** ******
//plus operation
template <typename TYPE>
inline const Vector<TYPEoperator+(const Vector<TYPE>& lhs, const
Vector<TYPE>& rhs)
{
* * * * return Vector<TYPE>(lhs) += rhs; * <----- (c)

}

//********************** END: VECTOR *************************
Hi,

I took the code, added a method to populate the vector and then it
failed to compile. I changed the following:

const Vector<TYPEoperator()(const int& i,const int& j) <---- (a)
return Vector<TYPE>(v, i, j);

to this:

const Vector<TYPEoperator()(const int& i,const int& j) // <---- (a)
{
return Vector<TYPE>(*this, i, j); // <--- Changed to pass in
*this, NOT v
}

and it worked. Your code was passing in the member variable v but
there's no constructor on Vector for std::vector! I don't know how you
got it to compile??

The following program seemed to work okay and outputs "3,4,5" to the
standard output:

/*------------------------------------------------
This is package for Vectors, Matrices (Template Class)
--------------------------------------------------*/
#include <iostream>
#include <vector>
#include <math.h>
#define to ,
using namespace std;
//********************** START: VECTOR *************************
template <typename TYPE>
class Vector {
vector<TYPEv;
public:
//************************************************** ******
// Selectors
const TYPE& operator[](const int& k) const { return v[k]; } //
default [] indexing
const TYPE& operator()(const int& k) const {return v[k];}
int size() const {return v.size();} //returns the size
const Vector<TYPEoperator()(const int& i,const int& j)
{
return Vector<TYPE>(*this, i, j);
}
//************************************************** ******
// Constructors and Destructor
Vector() { };
~Vector(){ };
//************************************************** ******
//plus operation
Vector<TYPE>& operator+=(const Vector<TYPE>& rhs){
for (int k = 0; k < rhs.size(); k++){
if (k < v.size())
v[k] += rhs[k];
else v.push_back(rhs[k]);
}
return *this;
}
//************************************************** ******
// Copiers
//copy constructors
Vector( const Vector<TYPE>& val) { //copy constructor for
intermediate results (like x + y)
for (int k = 0; k < val.size(); k++)
v.push_back(val[k]);
}
Vector( const Vector<TYPE>& val, const int& i, const int& j)
{
//this constructor is used to create copy when
indexing a range
for (int k = i; k <=j; k++){
if (k<val.size())
v.push_back(val[k]);
else v.push_back(0);
}
}
//assignments
Vector<TYPE>& operator=(const Vector<TYPE>& rhs) {
v.clear();
for (int k = 0; k < rhs.size(); k++)
v.push_back(rhs[k]);
return *this;
}

void add(const TYPE& t)
{
v.push_back(t);
}
};
//************************************************** ******
//plus operation
template <typename TYPE>
inline const Vector<TYPEoperator+(const Vector<TYPE>& lhs, const
Vector<TYPE>& rhs)
{
return Vector<TYPE>(lhs) += rhs;
}

int main()
{
Vector<intvi;
vi.add(1);
vi.add(2);
vi.add(3);
vi.add(4);
vi.add(5);
vi.add(6);

Vector<intcopyVec = vi(2,4);

std::cout << copyVec[0] << ',' << copyVec[1] << ',' << copyVec[2] <<
std::endl;

}
Sep 8 '08 #3
On 8 Sep, 10:02, maverik <maverik.m...@gmail.comwrote:
Hi fabian.
May be difference in this:

const Vector<TYPE*operator()(const int& i,const int& j) <---- (a)
{...}
* * * Vector<TYPE>& operator+=(const Vector<TYPE>& rhs){...}

Should you use:

const Vector<TYPE>& *operator()(const int& i,const int& j) <---- (a)
{...}

instead

const Vector<TYPE*operator()(const int& i,const int& j) <---- (a)
{...}
No. If he changed operator() to return a reference, it would return a
reference to the temporary which would be out of scope once operator()
has completed. The reference would be referring to a dead object.
Sep 8 '08 #4
Hi newbar and Maverik,

Thanks you both for your prompt reply. Newbar, I cant believe it
actually works. Yes you are right about lacking a constructor for
std:vector<TYPE>, actually I modified my code when i was posting and
made a mistake there.

The funny thing is I actually tried out the same thing you suggested
(before I posted), and I thought I saw that it didnt work, however
when I tried again after I read your post, it seemed to work. The only
thing is that I was programming on Windows before, and now I tried It
on a Mac.

I will go back to school tomorrow to try it out again on Windows.
On Sep 7, 11:22 pm, newbar...@gmail.com wrote:
On 8 Sep, 10:02, maverik <maverik.m...@gmail.comwrote:
Hi fabian.
May be difference in this:
const Vector<TYPE operator()(const int& i,const int& j) <---- (a)
{...}
Vector<TYPE>& operator+=(const Vector<TYPE>& rhs){...}
Should you use:
const Vector<TYPE>& operator()(const int& i,const int& j) <---- (a)
{...}
instead
const Vector<TYPE operator()(const int& i,const int& j) <---- (a)
{...}

No. If he changed operator() to return a reference, it would return a
reference to the temporary which would be out of scope once operator()
has completed. The reference would be referring to a dead object.


Sep 8 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents a rather good discussion of typecast operator overloading. I am presenting...
34
by: Pmb | last post by:
I've been working on creating a Complex class for my own learning purpose (learn through doing etc.). I'm once again puzzled about something. I can't figure out how to overload the assignment...
17
by: Chris | last post by:
To me, this seems rather redundant. The compiler requires that if you overload the == operator, you must also overload the != operator. All I do for the != operator is something like this: ...
6
by: jay | last post by:
In the c++ primer ,i get a program. A class's name is TT,and it define the operator overload! TT first; //constructor TT second(30);//constructor TT thrid(40://constructor...
2
by: allan.mcrae | last post by:
I am having trouble with overloading the += operator when template parameters are used. I have a class holding an array (called "derived" in the following example) which derives from a base class...
0
by: erik.erikson | last post by:
I am getting a compiler error that I can't well explain or even understand the origin of (though I boiled it down close...). Below is a bare-bones example. What I am doing is defining the...
3
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj,...
9
by: sturlamolden | last post by:
Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by...
22
by: clicwar | last post by:
A simple program with operator overloading and copy constructor: #include <iostream> #include <string> using namespace std; class Vector { private: float x,y; public: Vector(float u, float...
7
by: Rahul | last post by:
Hi Everyone, I was overloading the operator= function as a class member function, #include <iostream.h> class A { int value; public : A& operator = (const A& ref)
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.