473,396 Members | 1,812 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,396 software developers and data experts.

call copy constructor in "=" operator

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
{
public:

AA( AA & obj)
{
}

AA & operator=( AA & obj)
{
AA(obj);
return *this;
}

};

int main()
{

return 0;
}

pp.cc: In method `class AA & AA::operator =(AA &)':
pp.cc:11: declaration of `obj' shadows a parameter
pp.cc:11: no matching function for call to `AA::AA ()'
pp.cc:6: candidates are: AA::AA(AA &)

Feb 13 '06 #1
11 2668
* fo*********@gmail.com:

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
Style: don't use all uppercase names except for macros.

{
public:

AA( AA & obj)
{ * fo*********@gmail.com: }
Unless there is a very good reason to do something else, the argument to
the copy constructor should be a reference to const,

AA( AA const& other ) {}

AA & operator=( AA & obj)
{
AA(obj);
This would declare an object obj of type AA, _if_ type AA had a default
constructor and _if_ you didn't have a name conflict:

AA (obj);

means

AA obj;

and causes the compiler to issue
pp.cc: In method `class AA & AA::operator =(AA &)':
pp.cc:11: declaration of `obj' shadows a parameter
for the name conflict, and
pp.cc:11: no matching function for call to `AA::AA ()'
pp.cc:6: candidates are: AA::AA(AA &)
for the lack of a default constructor.

Probably what you intended was

AA copy( obj );

return *this;


At this point it's too early to return; you still have to update the
object assigned to!

What you have is a copy of the assignment source, and the idiom for
using the copy constructor in this way relies on then swapping the
contents of that copy and the object assigned to,

swap( copy );

where swap is a member function that swaps the contents and is
guaranteed to not throw.

Then you can return, and as part of that the swap the destructor is
responsible for destroying e.g. dynamically allocated memory earlier
held by *this but now residing in copy.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 13 '06 #2
fo*********@gmail.com wrote:
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
{
public:

AA( AA & obj)
{
}

AA & operator=( AA & obj)
{
AA(obj);
return *this;
}

};

int main()
{

return 0;
}

pp.cc: In method `class AA & AA::operator =(AA &)':
pp.cc:11: declaration of `obj' shadows a parameter
pp.cc:11: no matching function for call to `AA::AA ()'
pp.cc:6: candidates are: AA::AA(AA &)

That is not generally a good idea because a constructor
should not have to clean up any dynamically allocated
memory currently in use whereas the operator =() should
do. Hence your code could develop memory leaks and
GP faults!!

JB
Feb 13 '06 #3
fo*********@gmail.com wrote:
Dear All,

I am new to c++ and when write below code that try to call copy
constructor


You cannot call constructors. They are called for you when you
create an object .. and *only* when you create an object. When you do
assignment, you do not create anything. Maybe this helps in
understanding why you cannot call the copy constructor.

Obviously you are trying to reduce duplicate code. In this case, it
is usually a good idea to create little private helper functions that do
the job. My preference: destroy, create and copy. Your destructor calls
destroy, default constructor calls create, copy constructor calls copy
and the assignment operator first calls destroy and then copy etc.

hth
--
jb

(reply address in rot13, unscramble first)
Feb 13 '06 #4
Thanks All for the detailed explaination,
do you mean I can not call a constructor explicitly?

I've changed to use "this " to try to call constructor AA but failed
(but i think destructor can be called explicitly),

AA & operator=( AA & obj)
{
this->AA(obj);
return *this;
}
pp.cc: In method `class AA & AA::operator =(AA &)':
pp.cc:11: calling type `AA' like a method

Thanks!

Feb 13 '06 #5
<fo*********@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
: Thanks All for the detailed explaination,
: do you mean I can not call a constructor explicitly?
:
: I've changed to use "this " to try to call constructor AA but failed
: (but i think destructor can be called explicitly),
:
: AA & operator=( AA & obj)
: {
: this->AA(obj);
: return *this;
: }

It would be possible to re-construct the object (by using
placement-new), but constructing an object twice will lead
to undefined behavior.
I have also seen programmers try first force the destruction
of the object ( this->~AA() ) before copy-constructing it,
but then in many cases it is impossible to provide basic
exception safety, and the legality of it remains uncertain.

If your class is simple enough for any of the bad tricks above
to work, you are better off in any case to implement the
copy-constructor itself in terms of the assignment operator:
AA( AA const& obj )
{
*this = obj;
}

for more complex objects, a common idiom is to use the
swap-with-temp-copy idiom, which is the solution Alf
pointed you to:
AA& operator=( AA const& obj )
{
AA(obj).swap(*this);
return *this;
}
Implementing an efficient swap operation is a good idea
anyway for most of the complex objects that are assignable.
hth-Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Feb 13 '06 #6
dc
This is quite strange

Suppose AA has a constructor with arg int.
int inst;
.........
AA (inst);//Treats inst as a variable of AA.
AA(10);//OK

Feb 13 '06 #7
fo*********@gmail.com wrote:
Thanks All for the detailed explaination,
do you mean I can not call a constructor explicitly?


A constructor is - as the name suggests - part of construction of an object.
An object's constructor gets only called once, and that's when the object
is created.

Feb 13 '06 #8
* fo*********@gmail.com:
Thanks All for the detailed explaination,
do you mean I can not call a constructor explicitly?


See the reply from Ivan Vecerina.

What I think you mean by the question, namely, invoking a constructor on
an existing object, is something you absolutely don't want to do!

Also, be aware that (1) that's _not_ the same as an explicit constructor
call in the sense the term is used in the standard, and (2) that use of
the word "call" -- or even "invoke" -- in the context of constructor
whatchammacallitbutsomeutterancethatcausesthemtoex ecute, can have about
the same effect on some C++ programmers as the publishing of drawings of
Mohammed recently had on some fanatics: they'll go amok, berserk, etc.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 13 '06 #9

"dc" <de************@gmail.com> wrote in message

| This is quite strange

What is quite strange ? Please specify the context.

| Suppose AA has a constructor with arg int.
| int inst;
| ........
| AA (inst);//Treats inst as a variable of AA.
| AA(10);//OK

I can't see the point you are trying to make.

Sharad

Feb 13 '06 #10
dc wrote:
This is quite strange

Suppose AA has a constructor with arg int.
int inst;
........
AA (inst);//Treats inst as a variable of AA.
AA(10);//OK


The rule is: If it could compile OK as a declaration, then it is;
otherwise it isn't. :) Here's another example:

typedef int x;
class A { };

void foo()
{
A b(x); // declares function b taking int as parameter
// and returning an A (!)

A (x); // declares local variable named 'x'
// (hides the typedef)
A a(x); // creates object 'a' , passing local variable
// 'x' to its copy constructor

}

Feb 14 '06 #11
* Old Wolf:
dc wrote:
This is quite strange

Suppose AA has a constructor with arg int.
int inst;
........
AA (inst);//Treats inst as a variable of AA.
AA(10);//OK


The rule is: If it could compile OK as a declaration, then it is;
otherwise it isn't. :) Here's another example:

typedef int x;
class A { };

void foo()
{
A b(x); // declares function b taking int as parameter
// and returning an A (!)

A (x); // declares local variable named 'x'
// (hides the typedef)
A a(x); // creates object 'a' , passing local variable
// 'x' to its copy constructor

}


He he... :-) :-) :-)

The description "failed experiment" is very apt.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Feb 14 '06 #12

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

Similar topics

3
by: ¤ Alias | last post by:
I have a function named getID3info (lvwDiscInfo.SelectedItem). What is the difference between getID3info (lvwDiscInfo.SelectedItem) and Call getID3info(lvwDiscInfo.SelectedItem) ?
2
by: Nick Jacobson | last post by:
This question is with regard to the * operator as used for sequence concatenation. There's the well-known gotcha: a = ] b = a*3 b = 4 print b
9
by: Pierre Senellart | last post by:
The C++ standard states (26.3.2.1), about std::valarray constructors: > explicit valarray(size_t); > > The array created by this constructor has a length equal to the value of > the argument....
7
by: Vaca Louca | last post by:
Hello, My setup: Debian sarge on dual Pentium 4. g++ 3.3.5-3. (the other system is Windows XP with MS Visual Studio .NET 2003) I have an auto_array<T> template (based on a template taken from...
2
by: srktnc | last post by:
When I run the program, I get a Debug Error saying "This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more...
19
by: Martin Oddman | last post by:
Hi, I have a compiling problem. Please take a look at the code below. I have an application that is built upon three tiers: one data tier (Foo.DataManager), one business tier (Foo.Kernel) and...
1
by: RajS | last post by:
Hi All, I wanted increase time out on odbc connection, I have code like this this.odbcConnection1.set_ConnectionTimeout(1000); I got the following error "cannot explicitly call operator or...
4
by: Dan Stromberg | last post by:
Hi folks. I'm working on building some software, some of which is written in C++, for a researcher here at the University. I have an extensive background in C and python, but I haven't done...
3
by: Jess | last post by:
Hello, The C++ reference says the return result of "copy" is an output iterator. I'm wondering how I can assign the returned iterator to some other iterator. I tried int main(){ string...
1
by: jr.freester | last post by:
I've written a Matrix container class and overloaded the function call operator to return values at a specified index. Below is the member function double operator()(int a , int b) { if((a <...
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
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...
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...
0
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,...

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.