473,734 Members | 2,798 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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()(cons t int& k) const {return v[k];}
int size() const {return v.size();} //returns the size

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

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

//*************** *************** *************** ***********
//plus operation
Vector<TYPE>& operator+=(cons t 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<TYPEoper ator+(const Vector<TYPE>& lhs, const
Vector<TYPE>& rhs)
{
return Vector<TYPE>(lh s) += rhs; <----- (c)
}
//*************** ******* END: VECTOR *************** **********
Sep 8 '08 #1
4 2029
Hi fabian.
May be difference in this:

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

Should you use:

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

instead

const Vector<TYPE operator()(cons t int& i,const int& j) <---- (a)
{...}
Sep 8 '08 #2
On 8 Sep, 08:53, fabian....@gmai l.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()(cons t int& k) const {return v[k];}
* * * * int size() const {return v.size();} //returns the size

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

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

* * * * //*************** *************** *************** ***********
* * * * //plus operation
* * * * Vector<TYPE>& operator+=(cons t 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<TYPEoper ator+(const Vector<TYPE>& lhs, const
Vector<TYPE>& rhs)
{
* * * * return Vector<TYPE>(lh s) += 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<TYPEoper ator()(const int& i,const int& j) <---- (a)
return Vector<TYPE>(v, i, j);

to this:

const Vector<TYPEoper ator()(const int& i,const int& j) // <---- (a)
{
return Vector<TYPE>(*t his, 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()(cons t int& k) const {return v[k];}
int size() const {return v.size();} //returns the size
const Vector<TYPEoper ator()(const int& i,const int& j)
{
return Vector<TYPE>(*t his, i, j);
}
//*************** *************** *************** ***********
// Constructors and Destructor
Vector() { };
~Vector(){ };
//*************** *************** *************** ***********
//plus operation
Vector<TYPE>& operator+=(cons t 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<TYPEoper ator+(const Vector<TYPE>& lhs, const
Vector<TYPE>& rhs)
{
return Vector<TYPE>(lh s) += rhs;
}

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

Vector<intcopyV ec = 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...@g mail.comwrote:
Hi fabian.
May be difference in this:

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

Should you use:

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

instead

const Vector<TYPE*ope rator()(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...@g mail.comwrote:
Hi fabian.
May be difference in this:
const Vector<TYPE operator()(cons t int& i,const int& j) <---- (a)
{...}
Vector<TYPE>& operator+=(cons t Vector<TYPE>& rhs){...}
Should you use:
const Vector<TYPE>& operator()(cons t int& i,const int& j) <---- (a)
{...}
instead
const Vector<TYPE operator()(cons t 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
18568
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 below a summary of what I have gathered. I would appreciate if someone could point out to something that is specific to Borland C++ and is not supported by the ANSI standard. I am also concerned that some of the information may be outdated since...
34
6458
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 operator. Here's what I'm trying to do. I've defined class Complex as class Complex { friend ostream &operator<<( ostream &, Complex & ); public: Complex( float = 0.0, float = 0.0 );
17
2509
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: public static bool operator !=(MyType x, MyType y) { return !(x == y); } That way the == operator handles everything, and extra comparing logic isn't
6
2083
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 first=second.operator+; the question is the fourth line is all right?
2
2917
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 ("base"). I want to be able to add: 1) any derived array holding class to any other derived array holding class 2) any derived array holding class to a literal value (e.g int, double, etc) for which addition is defined for the type in the...
0
2052
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 increment operator in a class and then defining a derived class and using the derived class. When I try to use the increment operator on an instance of the derived class (as an instance of the derived class, not when used as an instance of the base...
3
3278
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, obj2 ;
9
3512
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 allowing the assignment operator (=) to be overloaded. One particular use for this would be to implement "lazy evaluation". For example it would allow us to get rid of all the temporary arrays produced by NumPy. For example, consider the...
22
3619
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 v);
7
1741
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
8946
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9449
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9310
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9182
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2724
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.