473,799 Members | 3,065 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

confusion with copy constructor and operator overloading

I've implemented a class with operator+ overloaded and I also provided
my own copy constructor; The problem is my copy constructor is being
called twise and I dont understand why. I believe the copy constructor
is being called when I add the two class objects. But if this is so,
then why because I have overloaded the + operator should I not get the
result from that and not from copy constructor?

I have the following:

int main(int argc, char *argv[])
{
CVector a(2,5);
CVector b(3,6);
CVector c;

c = a + b;

cout << "X: " << c.GetX() << " Y: " << c.GetY() << endl;

DisplayCopy(c);

system("PAUSE") ;
return EXIT_SUCCESS;
}

CVector CVector::operat or+(CVector param)
{
CVector temp;

temp.SetX( x + param.GetX() );
temp.SetY( y + param.GetY() );

return temp;
}

CVector::CVecto r(const CVector &rhs)
{
cout << "Inside Copy Constructor..." << endl;
x = rhs.x + 3;
y = rhs.y + 3;
}

void DisplayCopy(CVe ctor copy)
{
cout << "X: " << copy.GetX() << " Y: " << copy.GetY() << endl;
}

=============== =============== =============== =====

class CVector
{
public:
CVector(int valueX = 0, int valueY = 0): x(valueX), y(valueY) {}
CVector(const CVector &rhs); // Copy Constructor
CVector operator+(CVect or param);

int GetX() const { return x; }
int GetY() const { return y; }
void SetX(int valueX) { x = valueX; }
void SetY(int valueY) { y = valueY; }
protected:
int x, y;
};

void DisplayCopy(CVe ctor copy);

Jul 23 '05 #1
7 2552
"Kelly Mandrake" <at******@gmail .com> wrote in message
news:11******** **************@ c13g2000cwb.goo glegroups.com.. .
I've implemented a class with operator+ overloaded and I also provided
my own copy constructor; The problem is my copy constructor is being
called twise and I dont understand why. I believe the copy constructor
is being called when I add the two class objects. But if this is so,
then why because I have overloaded the + operator should I not get the
result from that and not from copy constructor?

I have the following:

int main(int argc, char *argv[])
{
CVector a(2,5);
CVector b(3,6);
CVector c;

c = a + b;

cout << "X: " << c.GetX() << " Y: " << c.GetY() << endl;

DisplayCopy(c);

system("PAUSE") ;
return EXIT_SUCCESS;
}

CVector CVector::operat or+(CVector param)
{
CVector temp;

temp.SetX( x + param.GetX() );
temp.SetY( y + param.GetY() );

return temp;
}

CVector::CVecto r(const CVector &rhs)
{
cout << "Inside Copy Constructor..." << endl;
x = rhs.x + 3;
y = rhs.y + 3;
}

void DisplayCopy(CVe ctor copy)
{
cout << "X: " << copy.GetX() << " Y: " << copy.GetY() << endl;
}

=============== =============== =============== =====

class CVector
{
public:
CVector(int valueX = 0, int valueY = 0): x(valueX), y(valueY) {}
CVector(const CVector &rhs); // Copy Constructor
CVector operator+(CVect or param);
You should pass the param by const reference.
For example:
CVector operator+(const CVector & param);
This will eliminate a copy as the parameter is passed.
int GetX() const { return x; }
int GetY() const { return y; }
void SetX(int valueX) { x = valueX; }
void SetY(int valueY) { y = valueY; }
protected:
int x, y;
};

void DisplayCopy(CVe ctor copy);


That parameter could also be passed by const reference.

--
--Larry Brasfield
email: do************* **********@hotm ail.com
Above views may belong only to me.
Jul 23 '05 #2
Kelly Mandrake wrote:
I've implemented a class with operator+ overloaded
and I also provided my own copy constructor; The problem is [that]
my copy constructor is being called twice and I don't understand why.
You pass the operands by value instead of const reference.
I believe the copy constructor is being called
when I add the two class objects.
But if this is so, then why because I have overloaded the + operator
should I not get the result from that and not from copy constructor? cat main.cc #include <iostream>

class CVector {
public:
CVector(int valueX = 0, int valueY = 0):
x(valueX), y(valueY) { }
CVector(const CVector &rhs); // Copy Constructor
CVector operator+(const CVector& param) const;

int GetX() const { return x; }
int GetY() const { return y; }
void SetX(int valueX) { x = valueX; }
void SetY(int valueY) { y = valueY; }
protected:
int x, y;
};

inline
CVector CVector::operat or+(const CVector& param) const {
return CVector(x + param.GetX(), y + param.GetY());
}

inline
CVector::CVecto r(const CVector &rhs) {
std::cout << "Inside Copy Constructor..." << std::endl;
x = rhs.x + 3;
y = rhs.y + 3;
}

inline
void DisplayCopy(con st CVector& copy) {
std::cout << "X: " << copy.GetX()
<< " Y: " << copy.GetY() << std::endl;
}

int main(int argc, char *argv[]) {
CVector a(2, 5);
CVector b(3, 6);
CVector c = a + b;

std::cout << "X: " << c.GetX()
<< " Y: " << c.GetY() << std::endl;

DisplayCopy(c);

system("PAUSE") ;
return EXIT_SUCCESS;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main

X: 5 Y: 11
X: 5 Y: 11
sh: line 1: PAUSE: command not found
Jul 23 '05 #3
I changed it now so that it takes a const reference and of cource it
works fine now. I can see it now that it calls copy constructor
because im passing by value but when I read my code over and over I
wasnt seeing this. Thanks for all the help everyone.

Jul 23 '05 #4
In reguards to Roberts post can I ask why it is you recoment moveing my
inline methods out of the class. Is this to do with a standard, please
explain because If it is a standard I will try to follow it from now
on.

Jul 23 '05 #5
Kelly Mandrake wrote:
In regards to Robert's post,
Can I ask why it is [that] you recommend
moving my inline methods out of the class.
Is this to do with a standard,
please explain because, if it is a standard,
I will try to follow it from now on.
I did *not* move any [inline] methods
out of your CVector class definition.
You *declared* CVector::operat or+(CVector)
and CVector::CVecto r(const CVector&)
in your CVector class definition
then *defined* them outside of the CVector class definition.
These are lightweight functions which should be inline'd
but they *must* be defined as inline functions
*before* they are invoked (in function main(int, char**) in this case).

"Standard" practice is to place the class definition
along with any inline function definition in a header file:
cat CVector.h #ifndef GUARD_CVECTOR_H
#define GUARD_CVECTOR_H 1

#include <iostream>

class CVector {
public:
CVector(int valueX = 0, int valueY = 0):
x(valueX), y(valueY) { }
CVector(const CVector &rhs); // Copy Constructor
CVector operator+(const CVector& param) const;

int GetX() const { return x; }
int GetY() const { return y; }
void SetX(int valueX) { x = valueX; }
void SetY(int valueY) { y = valueY; }
protected:
int x, y;
};

inline
CVector CVector::operat or+(const CVector& param) const {
return CVector(x + param.GetX(), y + param.GetY());
}

inline
CVector::CVecto r(const CVector &rhs) {
std::cout << "Inside Copy Constructor..." << std::endl;
x = rhs.x + 3;
y = rhs.y + 3;
}

#endif//GUARD_CVECTOR_H

then include it in each source file that references CVector:
cat main.cc #include "CVector.h"

inline
void DisplayCopy(con st CVector& copy) {
std::cout << "X: " << copy.GetX()
<< " Y: " << copy.GetY() << std::endl;
}

int main(int argc, char *argv[]) {
CVector a(2, 5);
CVector b(3, 6);
CVector c = a + b;

std::cout << "X: " << c.GetX()
<< " Y: " << c.GetY() << std::endl;

DisplayCopy(c);

system("PAUSE") ;
return EXIT_SUCCESS;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main

X: 5 Y: 11
X: 5 Y: 11
sh: line 1: PAUSE: command not found
Jul 23 '05 #6
Ok I see now what you mean that you simply added the keywords inline.
Ive been putting the definitions inside my class alot too. So these
are considered light weight because they only have a few lines, or is
there a rule of thumb to determine weather to make them inline or not.

Jul 23 '05 #7
I see, very intelegent. So realy I could make all my funbctions inline
and thus would speed up execution of my program but because it slows
down the compiler as it needs to copy and paste inline functions where
they are used, it would be usefull to use preprocessor comands as you
showed so that I can compile quickly while develping and then wehn its
time for a distribution to be made, i compile with all inline
functions.

I like this idea. I must take the time to learn the preprocessor
statements, ive been avoiding them but it seems they are realy usefull.
Thanks for all the help.

Jul 23 '05 #8

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

Similar topics

7
1385
by: raj | last post by:
I need explanation of the behavior of the following code. When run as it is, it gives error. //-------------------------<start>------------------ #include <iostream.h> #include <stdlib.h> class ABC { private: int x;
1
1973
by: Bob | last post by:
Hi, I'm trying to use a map with a string key, and a pointer to objects contained in a vector. I've wrapped this in a class like so: // cMap template<class T> class cMap : public cList<T> { // private: protected: std::map<std::string, T*> tMapOf; // map container
4
2624
by: Chris Mabee | last post by:
Hello all, and Merry Christmas, I'm having a problem understanding an example of an array based implementation of a stack in a textbook of mine. The code in question is written below. The syntax is directly as in the book, except for where I added the comments at the lines I wanted to refer to or to skip sections of code. template <class Element_Type> class Stack {
7
1788
by: pauldepstein | last post by:
A book I have describes a class called vector. It then explains (and I understand) the concept of a copy constructor, which is needed to interpret statements like vector b = a; But then I get confused when it speaks of overloading =, and explains that this concept is needed to interpret statements like b = a;
11
2706
by: fourfires.d | last post by:
Dear All, I am new to c++ and when write below code that try to call copy constructor in "=" operator overloading, it can not compile. Can anyone point out for me the reason? thanks !! class AA {
4
1753
by: coder_lol | last post by:
Given the template class below, please help me understand the following code behavior? Array<int32ia(10); // Array that can contain 10 int32 ia = 1; // Array element 1 set to 1 Here comes the confusion part. Array<int32*iarrayPtr = new Array<int32>(10);
22
3629
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);
0
1460
by: Donovan Parks | last post by:
Hello, I am rather lost about how to properly setup a copy constructors and operator= with my template class. My class if as follows: template<class Tclass Image { private: IplImage* imgp;
4
1362
by: hjast | last post by:
I'm trying to implement a = operater to set one circle or rectangle to another and this is giving me all kind of bugs. #include <iostream.h> class Shape { private: int x_Center, y_Center;
0
9546
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10491
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
10268
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...
1
10247
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10031
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...
0
9079
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6809
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();...
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.