473,779 Members | 2,015 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2703
* fo*********@gma il.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*********@gma il.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*********@gma il.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*********@gma il.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*********@gm ail.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.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(*t his);
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*********@gma il.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*********@gma il.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
whatchammacalli tbutsomeutteran cethatcausesthe mtoexecute, 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

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

Similar topics

3
46967
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
2245
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
3721
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. The elements of the array are constructed using the default > constructor for the instantiating type T. Does that mean that, on built-in types (e.g. int), "default initialization" (as described in 8.5) is performed?
7
5086
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 the Corona project hosted at SourceForge) which basically wants to implement std::auto_ptr<T> semantics for an array.
2
2576
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 information." I put a cout statement (//cout << "len of cPtr: " << _len << endl; ) in my constructor and see that _len is 3435973837 though my character pointer has only a few characters. Then I get the usual message as state above.
19
3581
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 one web presentation tier (Foo.WebFiles). The data tier shall only be accessible thru the business tier so I do NOT want a reference to the data tier in the presentation tier. In the business tier I have a class with the name CategoryItem that...
1
7718
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 accessor" How can I increase the time out? Thanks,
4
1896
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 much with C++ - I kind of mostly abandoned C++ some time ago, when I coded a project in C++, and some of my coworkers refused to use it -because- it was in C++.
3
1976
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 s("abcdefg"); vector<charv; vector<char>::iterator k = copy(s.begin(),s.end(),back_inserter(v));
1
3781
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 < 1) || (b < 1) || ((a + 1) this->row) || ((b + 1) this- { cerr << "Invalid index for Matrix" <<endl; }
0
9636
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
9474
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
10306
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...
1
10074
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
8961
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
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4037
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
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
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.