Copy constructor

Dear people,

I have a class C1 which contains a member variable of class C2.
C2 didn't have a copy constructor up to now but due to a
change needed (and got) one, and an assignment operator
as well. Now when compiling, I get en error C2558:
"class C1: No copy constructor available or copy constructor
has been declared 'explicit'". It is correct that C1 doesn't
have a copy constructor but I thought that the default copy
constructor just calls the assignment operators of the
members. Since C2 has an explicitly programmed
assignment operator - where is the mistake?

TIA!
0
Frank
5/10/2010 3:05:00 PM
vc.mfc 33608 articles. 0 followers. Follow

12 Replies
1284 Views

Similar Articles

[PageSpeed] 43

Yes, you will need to supply a copy constructor to C2 if you expect C1 to be copyable.  If
every component of C1 has a copy constructor, then C1 can be copied.  

A copy constructor and an assignment operator are quite different from the viewpoint of
C++, even if a copy constructor calls the assignment operator.  It's part of the deep
rules of C++ syntax.
				joe

On Mon, 10 May 2010 08:05:00 -0700 (PDT), Frank <jerk@gmx.de> wrote:

>Dear people,
>
>I have a class C1 which contains a member variable of class C2.
>C2 didn't have a copy constructor up to now but due to a
>change needed (and got) one, and an assignment operator
>as well. Now when compiling, I get en error C2558:
>"class C1: No copy constructor available or copy constructor
>has been declared 'explicit'". It is correct that C1 doesn't
>have a copy constructor but I thought that the default copy
>constructor just calls the assignment operators of the
>members. Since C2 has an explicitly programmed
>assignment operator - where is the mistake?
>
>TIA!
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
Joseph
5/10/2010 4:56:10 PM
On Mon, 10 May 2010 08:05:00 -0700 (PDT), Frank <jerk@gmx.de> wrote:

>Dear people,
>
>I have a class C1 which contains a member variable of class C2.
>C2 didn't have a copy constructor up to now but due to a
>change needed (and got) one, and an assignment operator
>as well. Now when compiling, I get en error C2558:
>"class C1: No copy constructor available or copy constructor
>has been declared 'explicit'". It is correct that C1 doesn't
>have a copy constructor but I thought that the default copy
>constructor just calls the assignment operators of the
>members. Since C2 has an explicitly programmed
>assignment operator - where is the mistake?

Constructors create objects where none existed before, while assignment
operators overwrite existing objects. Therefore, the default copy ctor
invokes only copy ctors, and the default assignment operator invokes only
assignment operators. They do this for each member variable and base class.
So, for your scenario, if any copy ctor is inaccessible or cannot be
generated, the compiler will not be able to generate a copy ctor for C1.

-- 
Doug Harrison
Visual C++ MVP
0
Doug
5/10/2010 5:34:12 PM
Doug Harrison wrote:

> Constructors create objects where none existed before, while assignment
> operators overwrite existing objects. Therefore, the default copy ctor
> invokes only copy ctors, and the default assignment operator invokes only
> assignment operators.

I see... so the copy constructor of C1 won't invoke
the assignment operators of its members to initialize
them like I thought?
0
Frank
5/11/2010 7:07:47 AM
On May 10, 5:05=A0pm, Frank <j...@gmx.de> wrote:
> Dear people,
>
> I have a class C1 which contains a member variable of class C2.
> C2 didn't have a copy constructor up to now but due to a
> change needed (and got) one, and an assignment operator
> as well. Now when compiling, I get en error C2558:
> "class C1: No copy constructor available or copy constructor
> has been declared 'explicit'". It is correct that C1 doesn't
> have a copy constructor but I thought that the default copy
> constructor just calls the assignment operators of the
> members. Since C2 has an explicitly programmed
> assignment operator - where is the mistake?

Assignment !=3D copy construction, hence:

class C1
{
C1(const C1& that);
C2 c2;
....
};

C1::C1(const C1& that) :
  ...,
  c2(that.c2), // Missing copy ctor here.
  ...
{}

Also, keep "the rule of three" in mind:
http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29

Goran.

0
Goran
5/11/2010 7:20:22 AM
"Frank" <jerk@gmx.de> ha scritto nel messaggio 
news:98d7f241-37f7-4d59-b6f9-40956bb9716c@24g2000yqy.googlegroups.com...

> I see... so the copy constructor of C1 won't invoke
> the assignment operators of its members to initialize
> them like I thought?

Doug was very clear in his post: the copy constructor of C1 will just invoke 
the *copy constructors* (not operator=) of its data members.

Giovanni
 

0
Giovanni
5/11/2010 7:43:12 AM
Giovanni Dicanio wrote:

> Doug was very clear in his post: the copy constructor of C1 will just invoke
> the *copy constructors* (not operator=) of its data members.

Ok... so the question remains: Why doesn't C1 have a
copy constructor anymore from the moment I wrote one
for one of its members?
0
Frank
5/11/2010 8:59:58 AM
On May 11, 10:59=A0am, Frank <j...@gmx.de> wrote:
> Giovanni Dicanio wrote:
> > Doug was very clear in his post: the copy constructor of C1 will just i=
nvoke
> > the *copy constructors* (not operator=3D) of its data members.
>
> Ok... so the question remains: Why doesn't C1 have a
> copy constructor anymore from the moment I wrote one
> for one of its members?

Perhaps you should show the code that exhibits the behavior. Also, you
should try to compile it with e.g. comeau online.

Goran.
0
Goran
5/11/2010 11:46:00 AM
Goran wrote:

> On May 11, 10:59=A0am, Frank <j...@gmx.de> wrote:
>
> > Giovanni Dicanio wrote:
> > > Doug was very clear in his post: the copy constructor of C1 will just=
 invoke
> > > the *copy constructors* (not operator=3D) of its data members.
>
> > Ok... so the question remains: Why doesn't C1 have a
> > copy constructor anymore from the moment I wrote one
> > for one of its members?
>
> Perhaps you should show the code that exhibits the behavior. Also, you
> should try to compile it with e.g. comeau online.

Yes, thanks, I'll strip it down a bit because I found a
solution now but don't understand it - it works if I
make the parameter of the copy constructor of C2
a "const":

This works:

class C2
{
  ...

  C2(const C2 &cRHS)
  {
    AssignData(cRHS);
  }
}

This doesn't work:

class C2
{
  ...

  C2(C2 &cRHS)
  {
    AssignData(cRHS);
  }
}
0
Frank
5/11/2010 1:18:13 PM
"Frank" <jerk@gmx.de> wrote:


> This works:
> 
> class C2
> {
>  ...
> 
>  C2(const C2 &cRHS)

> This doesn't work:
> 
> class C2
> {
>  ...
> 
>  C2(C2 &cRHS)

I think this is because the usual pattern for copy ctor for class X is:

  X::X( const X & )


Giovanni
 
0
Giovanni
5/11/2010 2:26:31 PM
On May 11, 3:18=A0pm, Frank <j...@gmx.de> wrote:
> This doesn't work:
>
> class C2
> {
> =A0 ...
>
> =A0 C2(C2 &cRHS)

That should be const, to assure that you don't change cRHS there
(normally, you want to make a copy of an object, not to make a copy
and change the original). Is it that C1 has this:

C1::C1(const C1&rhs)?

(if C1 has a default copt ctor, that's it's "invisible declaration").

there, rhs is const, and so C2 instance inside rhs is const. But C2
ctor wants a non-const reference, and you didn't give it that.

Goran.
0
Goran
5/11/2010 2:44:28 PM
Goran wrote:

> Is it that C1 has this:
>
> C1::C1(const C1&rhs)?
>
> (if C1 has a default copt ctor, that's it's "invisible declaration").

Many thanks - so this is the solution. C1 doesn't have
an explicit copy constructor, so it uses the default which
has a "const" argument, as you say.
0
Frank
5/11/2010 2:56:28 PM
In article <4457d090-6b1e-41d4-932b-
dcbf971d009f@l31g2000yqm.googlegroups.com>, jerk@gmx.de says...

[ ... ]

> Yes, thanks, I'll strip it down a bit because I found a
> solution now but don't understand it - it works if I
> make the parameter of the copy constructor of C2
> a "const":

Yes -- if you have a type T, the parameter for its copy ctor should 
be 'T const &'.

It's const for two reasons: first of all, a temporary can be bound to 
a reference to const T, but cannot be bound to a reference to (non-
const) T. Second, a (normal) copy ctor has no business modifying what 
it's copying in any case.

As far as what the "normal" refers to above, C++ 0x adds the concept 
of an 'rvalue reference'. The basic idea is that *if* you're copying 
a temporary object that's going to be destroyed after copying anyway, 
you can move the data from one object to another instead of making a 
whole new copy of the data, then destroying the old one. Especially 
for classes that contain large, dynamically allocated data (e.g. a 
string or vector) you can gain quite a lot of speed by "stealing" the 
data instead of copying it (typically doing a shallow copy instead of 
a deep copy).

-- 
    Later,
    Jerry.
0
Jerry
5/11/2010 3:59:47 PM
Reply:

Similar Artilces:

copy hard drive?
Hello group, I am running out of space on my hard drive and want to migrate to a larger one. Can I "copy" my current hard drive onto a larger one? Is it necessary to purchase software to do so. PC running SP with all the SP packages. Also would hate to have to reinstall the many programs involved. Thanks. rc wrote: > Hello group, > > I am running out of space on my hard drive and want to migrate to a larger > one. Can I "copy" my current hard drive onto a larger one? Is it necessary > to purchase software to do so. PC running SP...

Macro to copy macros
Hello, Is there a way to copy a macro from one workbook to another using a macro? Bill See Chip Pearson's site Bill http://www.cpearson.com/excel/vbe.htm -- Regards Ron de Bruin (Win XP Pro SP-1 XL2000-2003) www.rondebruin.nl "Bill" <sorry_no_spam@aol.com> wrote in message news:403a4800$1@usenet01.boi.hp.com... > Hello, > > Is there a way to copy a macro from one workbook to another using a macro? > > Bill > > Thanks Ron. It seems to work, though it is coincidental with my use of this method that I was warned of a "Bloodhound" v...

Copy-Paste ever changing ranges
On Sheet 2 I have ranges in column C, column E and column G all of different lengths and all changing in size as data is added, but all starting in row 3. What I would like to do is to copy the range from Sheet 2, column C to column A in Sheet 3 starting at cell A2, then directly below, paste a copy of the range from sheet2, column E, and then directly below paste a copy of the range from sheet 2, column G. Make sense? I am thinking code on a button would be apt? any thoughts. Sandy By ranges, I assume you mean named ranges. If so, copy this code and paste it into a standard modu...

copy comments to word
Hi, I'm having difficulties writing code to copy comments to word. I'm confused on the "Selection" and/or "Range" Values and how to use them in this situation. I need to be able to highlight a range of cells in excel... Then, copy all the comments in the selected area to a word document. I have ran across code that will copy the whole workbooks comments but that is not needed for this. Thanks for all the help. Strikker The following code will copy the comments in the selected range to Word: '============================== Sub CopySelectionCommentsToWord...

If Statement that Copies to another Sheet
I am not sure how to create an IF statement that does the following: If a cell is >1 then copy the contents of another cell onto another sheet. Can this be done? And does this make sense Thank you for your help!! :confused: --- Message posted from http://www.ExcelForum.com/ It can't be done - worksheet functions can only return values to their calling cells. However, you can put this in the cell in your second sheet: J1: =IF(Sheet1!A1>1, Sheet1!B1, "") which will display the contents of Sheet1!B1 if Sheet1A1 > 1, else will display a null string. In...

Copy Paste Special Macro
I need to copy the value of a formula into a cell one down and one to the left of the current cell I am copying. Rather then right click and select the options. I can build a macro to copy then paste special but...I want the copy to be the current cell I am in then move the active cell on down and one left then paste special. Is there a way to use visual basic to move one cell left and one cell down and move only the information in the cell? The following sub will do what you want: Sub DownAndLeft() Dim x As Variant x = Selection.Value Selection.Offset(1, -1) = x End Sub Select the ...

Copying an Array Formula
How do you copy an array formula from one cell to another -- montag ----------------------------------------------------------------------- montagu's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=1522 View this thread: http://www.excelforum.com/showthread.php?threadid=38759 montagu Wrote: > How do you copy an array formula from one cell to another? 1. Go to your original cell 2. Ctrl-C 3. Go to your other cell where you want the formula copied 4. Ctrl-V Regards. -- BenjieLop ------------------------------------------------------------------------...

Macro to copy text between two different delimeters
I am trying to write a macro in Excel to select text between cells which contain words. Two challenges: 1.) I need to search for a cell that contains only one-single word "item:" and then copy the contents of the cell just-above that cell 2.) I need to search for a cell that contains only one-single word "component(s):" and then copy all of the rows below that until I find a cell that contains only the word "Zip" Any samples would help for either of these challenges ~Vic This is just an example of technique, not a full solution. This macro searches the activ...

File placement with copied sheets
I have a spread sheet built that currently has 382 sheets of data. The sheets are 12 columns x 61 rows. There are conditional formats applied. I can copy a blank sheet move it to the required location, input data, but it will not let me save it. I get an error box to send to Microsoft. When I close it will go to recovery and updates the file as version1, version 1 version 2 ect... Hi, Save a copy of the workbook and delete some sheets (say) a dozen. Can you create new sheets and save now? If so I suspect you may have run out of system memory which is the limiting factor for...

Copy Multiple Sheets
How can I copy multiple sheets (2-5) to a new workbook. I know I can do a savea as, but then I lose the original, unless I reopen it. TIA Greg Click on the tab for sheet 2, hold down shift and then click on the tab for sheet 5. Now right click and select 'move or copy', then select new book from the top dropdown, tick the 'create a copy' at the bottom of the dialog box and hit OK. -- Regards Ken....................... Microsoft MVP - Excel Sys Spec - Win XP Pro / XL2K & XLXP ----------------------------------------------------------...

Copy Sheet and move to end
Hi, i have posted something similar earlier today but this is alittle different. I have a sheet called Template in a workbook. i need to be able to issue a macro that will copy it and move it to the far right after all other sheets. Then rename it 1 number above the last sheet. i.e. if the last sheet was 2567 then my new copied shett will be 2568. regards, N.S. Sheets("TEMPLATE").Copy After:=Sheets(Sheets.Count) ActiveSheet.Name = Sheets.Count HTH -- (][ THIS EMAIL HAS BEEN SCANNED BY NORTON ANTIVIRUS ][) "Nigel" <Nigel@discussions.microsoft.com> wrote in ...

Copy Files from '2002' Money...
....on main computer to laptop "2002' Money. I back-up to CD or Memory Stick...plug into laptop... hit restore from back-up and it says password needed. I have no password on original. I am signed on to same passport password on both computers also... HELP!!! In microsoft.public.money, NeedingHelp wrote: >...on main computer to laptop "2002' Money. > I back-up to CD or Memory Stick...plug into laptop... hit restore from >back-up and it says password needed. I have no password on original. I am >signed on to same passport password on both computers also......

deleting old .pst files and copying to new PC
Now using Outlook 2007. Through fits and starts I've wound up with multiple pst files. I can tell from the dates which ones no longer apply. When I delete these, are their supporting files I should delete too? Secondly, if I copy all the files from the directory to laptop for a winter vacation, what settings do I need to modify on the laptop copy of Outlook for it to work? Thanks for you help! Kim The first thing you must realize is that you must never do anything to a PST file in Windows Explorer until you have disconnected it from an Outlook profile. After that ...

HELP copy and paste
I am trying to copy a range of cells and paste them after every Total This is what I have so far: Sub b8pastetitle() Dim theRange As Range Dim lastrow&, firstRow&, x& Set theRange = ActiveSheet.UsedRange lastrow = theRange.Cells(theRange.Cells.Count).Row firstRow = theRange.Cells(1).Row For x = lastrow To firstRow Step -1 If InStr(1, Cells(x, 1), "Total") > 0 Then Range("A5 : G7").Select Selection.Copy ActiveSheet.Paste Destination:=Worksheets("Payroll").Cells(x + 2, 1).Selection.Paste End If Next End Sub -- Stacia Plea...

Help with a Copy and Paste Macro
I tired to get an answer for this over in excel.function over the last week, but I wasn't able to get an answer. Hopefully someone over here that doesn't check that will be able to help me out. Here is my problem. I have this macro that takes a line and copies it to the end of a list on another tab. The one problem? I need it to Paste special - Values. And if you can write a better macro then this one that does what I need, please do. I just need it to work correctly. Thanks Tyson Sub copytolist() Sheets("Data Enter").Activate Range("A2:C2").Copy De...

Copying an excel worksheet
I have a two worksheet excel document. The first worksheet has all the raw data and formulas. The second worksheet has some nice table layout with the final results imprted from the first worksheet. What I need to do is copy just the data (results) and tables from the second worksheet without any of the formulas or macros to a brand new excel document that can be submitted for presentation. I have tried highlighting all the cells in the first excel sheet and then doing a copy and finally a paste in the new document, but get the message "Data on the clipboard is not the same size...

Copying spreadsheet with formulas
Hello, I would like to copy a fairly large spreadsheet retaining the formulas but without the data which I inputted. I appreciate your help Thanks, Bert -- Message posted from http://www.ExcelForum.com Hi Bert This example will copy all worksheets in a new workbook and delete all constants You can also run it on a copy of the workbook if it is active Delete the <Worksheets.Copy> then Sub test() Dim sh As Worksheet Worksheets.Copy For Each sh In ActiveWorkbook.Sheets On Error Resume Next sh.Cells.SpecialCells(xlCellTypeConstants).ClearContents On Error GoTo 0 Next sh End Sub -- Re...

Need macro to copy a hidden row
I have a spreadsheet with rows 701 identical rows [rows 6 - 706]. These rows contain formulas, data validation, merged cells, and conditional formats. As I enter data into the rows, I sometimes need to go back and insert a row with the same formulas, validation, merged cells, etc. I thought the best way to accomplish this would be to hide row 6 (as I sometimes will change one of the rows by adding an @sum or something, so I can't be sure that the row above where I currently am working is unaltered, so I figured to use a hidden row as a "template") then access it [row 6] to copy a...

Copy worksheet to new workbook : Values & Formats
Hi, Is it possible to cpy an entire worksheet (Values & Formats) to a new workbook without copying formulas ? Sheets(X).Copy is building links to previous workbook. Thks for help After coping go to Edit->Links, and break links, and excel will replace links with values. If you do it from VBA, which seems so, try with PasteSpecial metod. "Franck" <wesley.saris@gmail.com> wrote in message news:1130320762.209498.135290@g43g2000cwa.googlegroups.com... > Hi, > Is it possible to cpy an entire worksheet (Values & Formats) to a new > workbook without copying f...

VBA Copy Paste Issue
I have a workbook that is used by multiple users and the copy paste lines of the code do not work on the newer computers. It gets hung up when I code Range("A1:A5").copy Range("A1").pasteSpecial Xlvalues. I do not understand why this does not work on all computers. It errors out and tells me that it can not paste because the range is nto the same. So then I have to speciff Range("A1:A5") to paste.....this does not make sense to me. Thanks, Jay ...

Copy down (propagate) function/forumula needed
I have a project I'm working on where I get a huge spreadsheet and I need to "massage" the data to make it ready to load into a database. There are two issues ~ The data I want to "copy down" is in the first column. For example cell A1="some data", A2 A3 A4 are blank, A5="some data", A6 A7 are blank, A8="other data", etc. so... I want to be able to propagate whatever is in the first cell down through the all cells below whether the cell is blank -or- the cell has the same value (see cell A5). When a cell value changes, then the n...

Copy & Paste issues with "Quotes"
Hello All - I'm having an issue when I copy data from my POS software and then paste it into Excel. I believe the issue revolves around the use of " in certain fields. For example, one of the lines that I'm having problems with looks like this when I copy it to Notepad: "AVN12223" "Pipe Extension - 3"" 336.40" "Accessory" "9" "Each" When I copy the same data on the clipboard to Excel it comes out like this AVN12223 Pipe Extension - 3"336.40Accessory 9 Each As yo...

excel vba
I have set up my sheet to protect using a password name login which the runs the macros. It is set up so that the sheet's cells cannot b edited, but the person can copy/paste the info onto another sheet. This is a problem because there are hidden cells which contai sensitive data. Any ideas -- Message posted from http://www.ExcelForum.com Hi, just a comment that i just found out, check out this link that I was refered too. That password that you setup doesn't do squat when you have access to this... http://www.straxx.com/excel/password.html I was mad when I saw this, when mean...

Cell truncated to 256 characters during copy to new worksheet
When you copy a cell which has greater than 256 characters from one worksheet to another the cell gets truncated to 256 characters. I have used the workaround suggested in the MS knowledge base. Does anyone else have any ideas? Brad Was the suggestion in the KB to copy the worksheet, then come back and copy the cells, then paste the cells? If it was, then I don't have another suggestion. If it wasn't, then I do. Brad Backlin wrote: > > When you copy a cell which has greater than 256 characters > from one worksheet to another the cell gets truncated to > 256 char...

error copying file or folder
I get the following error when copying Outlook messages to a folder in my file server. "error copying file or folder- Not enough storage available to process this command" I have plenty of storage on source and target computers. Any help would be greatly appreciated. Thank you. ...