What are the differences between C-string and new char[] constructors in C++?
Thread starteryungman
Start date
Click For Summary
The discussion focuses on the differences between using C-strings and dynamic memory allocation with `new char[]` in C++ constructors. The first constructor copies a C-string into a fixed-size array, while the second allocates memory dynamically, requiring a destructor to manage memory. Participants note that both constructors can achieve deep copying, but the dynamic allocation introduces complexity without clear advantages when fixed sizes are sufficient. The conversation highlights the importance of understanding memory management and the implications of using pointers versus fixed arrays in class design. Ultimately, using fixed-length arrays simplifies the code by avoiding the need for custom destructors and copy constructors.
Note that #include <iomanip> is the same place where you get setw(), setprecision() and the other stream manipulators that Gaddis discusses in section 3.8.
@Mark44 maybe it's archaic of me to do so, but I put a comment on every line of my mainframe or PC assembly language code, even if what the instruction is doing is obvious or should be obvious ##-## I do that based on the it can't hurt principle ##-## if a full explanation is warranted, I'll write it on non-instruction lines ##-## otherwise, I don't see why I should unnecessarily let an unexplained instruction go by.
#33
yungman
5,741
294
sysprog said:
@Mark44 maybe it's archaic of me to do so, but I put a comment on every line of my mainframe or PC assembly language code, even if what the instruction is doing is obvious or should be obvious ##-## I do that based on the it can't hurt principle ##-## if a full explanation is warranted, I'll write it on non-instruction lines ##-## otherwise, I don't see why I should unnecessarily let an unexplained instruction go by.
I wrote those comments for copying into my notes. I know I will forget what I am doing in the future thanks to the old brain. I just want to explain it in my notes. Actually here is the page of notes I just put in yesterday. You can see the same program with comments.
I put even more comments in the Overloading Constructor as you can see. I even use different colors for words as it's easier for me to read so I won't jump lines.
For me, it's a whole lot more important to actually print out a detail description when running the program where the code goes. I put in extra effort to line things up and make it easy to compare
In assembly language you work with registers which have fixed names and there is no such thing as a type so a comment like
Code:
mov ebx, message ;Set ebx to point to the beginning of a null-terminated message string.
is worthwhile. In a high level language, code like
C++:
char[] message = "This is a message";
needs no comment, and there are at least two good reasons you should NOT add unnecessary comments.
#35
yungman
5,741
294
pbuk said:
In assembly language you work with registers which have fixed names and there is no such thing as a type so a comment like
Code:
mov ebx, message ;Set ebx to point to the beginning of a null-terminated message string.
is worthwhile. In a high level language, code like
C++:
char[] message = "This is a message";
needs no comment, and there are at least two good reasons you should NOT add unnecessary comments.
I miss assembly languages. I don't understand why they don't use assembly language more, it's a lot smaller, a whole hell of a lot faster. People don't need new version of software every day. I am not going to start the ranting how the newer stuffs with software and firmware are slow and all.
#36
sysprog
2,617
1,796
@yungman please read one or more of @Mark44's AVX 512 Insight articles such as https://www.physicsforums.com/insig...isters-for-conditional-arithmetic-conclusion/. For the benefit of many readers, Mark has written brilliantly and patiently regarding computer programming, including, sometimes especially for you, regarding many specfic things about C++, and you have been helpful numerous times, sometimes just by providing cogent questions. Please let's not forget, and I trust that you don't, what a great guide @Mark44 is ##\dots##
#37
sysprog
2,617
1,796
Oh and, I think that @pbuk and @Jarvis323 are worthy of favorable mention, too. I think that real programmers do programming at least partly because they love it ##-## maybe your beloved granddaughter is already a real programmer, @yungman, just as you are a real engineer.
@Mark44 maybe it's archaic of me to do so, but I put a comment on every line of my mainframe or PC assembly language code, even if what the instruction is doing is obvious or should be obvious ##-## I do that based on the it can't hurt principle ##-## if a full explanation is warranted, I'll write it on non-instruction lines ##-## otherwise, I don't see why I should unnecessarily let an unexplained instruction go by.
I put comments on nearly all of the lines of assembly code I write, both in x86 and MIPS (the latter for the class I teach). In high-level language, comments aren't as necessary, provided that you use self-explanatory names. In any case, a comment shouldn't restate what the code is doing -- it's better to say why something is happening.
An example of a useless comment on non-self-documenting code:
C++:
l = 80; // x is set to 80
Better:
C++:
const int LINE_LEN = 80; // Length of a screen line in bytes
#39
sysprog
2,617
1,796
And then there are lines that not only shouldn't be commented, but also shouldn't be written in the first place, e.g.
CARDLEN EQU 80 CARDS ARE 80 CHARACTERS LONG
that's a waste of a card.
#40
Jarvis323
1,247
988
I'll just add that sometimes the act of writing the comments can help you better clarify and understand your own code. And striving to write better comments, by making them more clear, concise, and informative, can also help you gain a more clear and concise understanding.
Also, sometimes comments about a block of code rather than just a line can be helpful.
I often actually start coding up an algorithm by starting with blocks of comments, that enumerate the steps I need to go through. Then I go one by one and add the code corresponding to each block of comments below it. That's just me, but you might try this out if you get stuck sometime.
When I worked in industry, we had a consultant whose advice somehow morphed from "code should have about as many comments as lines" to "every line should have a comment". Needless to say, that didn't help. We got comments like:
C++:
++i; // Increments i by 1
and
C++:
a = a +b; // Adds b to a
I would also argue that having too many comments is almost as bad as having too few. It causes the important ones to be lost in a sea of trivia. And this from a person who wrote code that had a page or page and a half of comments before the first line of active code. (It was a union of structs, and there was a good reason to do it that way, and the first line of the comment block was a warning not to touch the code without a real good reason).
@Mark44 mentions that comments should tell why, not what. He could have elaborated on this, because it is very good advice. It also dovetails with his earlier advice on picking descriptive variable names. I would consider:
C++:
--n; // Decrements n by 1
to be inferior to:
C++:
--NumberOfWidgets; // At this point NumberOfWidgets is one more
// than the last Widget. This is needed to fix this.
I think the main exceptions to "tell why not what" is to document side effects or other unexpected or non-obvious behavior:
C++:
SpecializedPrint(a,b); // A side effect of Specialized Print is to zero *b
#42
yungman
5,741
294
Can anyone help me why I have an error on this? I simplified the program to the barebone:
C++:
#include <iostream>
#include <cstring>
using namespace std;
class PersonInfo
{ private: char* name; int age; const int Nsize = 51;
public:
PersonInfo(const char* n, int a) // Constructor
{ name = new char[strlen(n)+1];
strncpy_s(name, strlen(n) + 1, n, strlen(n) + 1) ; age = a;}
PersonInfo(const PersonInfo &obj) // Copy Constructor
{name = new char[strlen(obj.name)+1];
strncpy_s(name, strlen(obj.name) + 1, obj.name, strlen(obj.name) + 1);
age = obj.age;
}
~PersonInfo() { delete[] name; }
};
int main()
{ PersonInfo bob("Bob Faraday", 32);
PersonInfo clone("clone", 44);
clone = bob;//copy constructor
return 0;
}
I had this program, it was working, I don't see any problem. I am blind on this, it's supposed to be simple!
I had this program, it was working, I don't see any problem. I am blind on this, it's supposed to be simple!
You have a copy constructor, but you don't have an overloaded assignment operator; i.e., operator=().
The line clone = bob;//copy constructor needs to have operator=(), but you didn't write one.
Also, your comment is wrong -- this line is not calling a copy constructor. A wrong comment is worse than no comment at all.
Also, your code doesn't use Nsize, so why is it there? Even if there is a good reason, it shouldn't be const int in the class definition.
#44
yungman
5,741
294
Mark44 said:
You have a copy constructor, but you don't have an overloaded assignment operator; i.e., operator=().
The line clone = bob;//copy constructor needs to have operator=(), but you didn't write one.
Also, your comment is wrong -- this line is not calling a copy constructor. A wrong comment is worse than no comment at all.
Also, your code doesn't use Nsize, so why is it there? Even if there is a good reason, it shouldn't be const int in the class definition.
Thanks for the reply
It's really funny, I have it in my notes that actually ran the program, you can see I can do immediate window. You look at the code, there's no assignment operator. That's where I got tripped. It obviously was working, I got everything.
Thanks
Attachments
Copy Const4.docx
143.6 KB
· Views: 214
#45
Jarvis323
1,247
988
Another thing is that your code is formatted in what most people would consider a not-so-great way.
I would usually avoid putting multiple statements on one line. And I would separate statements with whitespace. Also, I would rarely put a statement on the same line as a { or }, unless it's a single line of code.
The idea is to help the reader see how the code is separated individual statements, or highly related sections at a glance, and that makes the code easier to understand quicker. And it also makes you less prone to error as you edit the code.
You might want to try using the autoformatting features of VS.
It's really funny, I have it in my notes that actually ran the program, you can see I can do immediate window. You look at the code, there's no assignment operator. That's where I got tripped. It obviously was working, I got everything.
The part of your code where you show the immediate window doesn't also show main(), so I'm not certain you ran the code you showed a few posts back. The part with main() is below the screen shot with the immediate window. That part also has the same incorrect comment -- "clone = bob;//copy constructor"
Again, this code assumes that you have an overloaded assignment operator -- you don't.
I believe the code you showed a few posts back. I don't believe that the code you have in your notes actually ran without error.
Jarvis323 said:
I would usually avoid putting multiple statements on one line.
Strongly agree. @yungman, packing so many statements on one line makes your code hard to follow. Please stop doing this.
Jarvis323 said:
And I would separate statements with whitespace. Also, I would rarely put a statement on the same line as a { or }, unless it's a single line of code.
Also very good advice.
#47
sysprog
2,617
1,796
It can be hard on the ego to admit it, but I think that in his case it's not really too hard ##-## I'm convinced that Prof. Don is better at programming than I am ##-## thank you for taocp and for ##\mathrm{\TeX},## Professor, which are among the many things for which programmers and others are to be grateful to you, perhaps not the least of which is the concept of literate programming.
Last edited:
#48
Jarvis323
1,247
988
sysprog said:
It can be hard on the ego to admit it, but I think that in his case it's not really too hard ##-## I'm convinced that Prof. Don is better at programming than I am ##-## thank you for taocp and for ##\mathrm{\TeX},## Professor, which are among the many things for which programmers and others are to be grateful to you, perhaps not the least of which is the concept of literate programming.
I've not heard of literate programming. Interesting concept.
#49
yungman
5,741
294
Hi
I am really out of idea. This is the program I am experimenting. I put const int Nsize = 51; into comment, then it will run. It gave me
C++:
#include <iostream>
#include <cstring>
using namespace std;
class PersonInfo
{
private: char *name; int age; //const int Nsize = 51;
public:
PersonInfo(const char *n, int a) // Constructor
{
name = new char[strlen(n) + 1];
strncpy_s(name, strlen(n) + 1, n, strlen(n) + 1);
age = a;
}
PersonInfo(const PersonInfo &obj) // Copy Constructor
{
name = new char[strlen(obj.name) + 1];
strncpy_s(name, (strlen(obj.name) + 1), obj.name, (strlen(obj.name) + 1));
age = obj.age;
}
// Accessor functions
const char* getName() { return name; }
const int getAge() { return age; }
~PersonInfo() { delete[] name; } // Destructor
};
int main()
{
PersonInfo bob("Bob Faraday", 32);
PersonInfo clone("clone", 44);
clone = bob;//copy constructor
cout << " The bob Object contains: " << bob.getName() <<
", age = " << bob.getAge() << endl;
cout << " Clone object name = " << clone.getName() <<
", age = " << clone.getAge() << "\n\n";
return 0;
}
The abort info is this, but you can see the result is out and is correct:
But if I put const int Nsize = 51 back in as shown, it will give me this error:
I don't know how to explain. I am not saying that I don't need operator=(), like Mark suggested. I just want to know why I went this far without it, but adding const int Nsize = 51 blows up everything.
I did make it one code line per line. I just too stuck with the problem.
Thanks
BTW, don't look at my notes to judge on how many lines of code packed into one line. I pack that to save pages and pages extra. That's my own notes, not for anyone else to read, just for me. Or else, it will be over 100 pages!
Last edited:
#50
Jarvis323
1,247
988
Solution is defining operator=.
Explanation: Like Mark pointed out, line 29 is not calling the copy constructor, it's calling operator=. You didn't define an operator=, so it would use the default one, which just does a shallow copy. Then when both copies go out of scope, they each call delete on the same memory address (in their destructors), which is why you get that runtime error (you should never call delete on the same address twice).
The reason it doesn't compile in the uncommented version is that C++ will "delete"
the default operator= in certain cases, forcing you to either define it yourself or not use it. Having a const member happens to be one of those conditions, as you can see in the below link under the section quoted,
Deleted implicitly-declared copy assignment operator
A implicitly-declared copy assignment operator for class T is defined as deleted if any of the following is true:
T has a user-declared move constructor;
T has a user-declared move assignment operator.
Otherwise, it is defined as defaulted.
A defaulted copy assignment operator for class T is defined as deleted if any of the following is true:
T has a non-static data member of non-class type (or array thereof) that is const;
T has a non-static data member of a reference type;
T has a non-static data member or a direct or virtual base class that cannot be copy-assigned (overload resolution for the copy assignment fails, or selects a deleted or inaccessible function);
T is a union-like class, and has a variant member whose corresponding assignment operator is non-trivial.
Explanation: Like Mark pointed out, line 29 is not calling the copy constructor, it's calling operator=. You didn't define an operator=, so it would use the default one, which just does a shallow copy. Then when both copies go out of scope, they each call delete on the same pointer (in their destructors), which is why you get that runtime error (you should never call delete on the same address/pointer twice).
The reason it doesn't compile in the uncommented version is that C++ will "delete"
the default operator= in certain cases, forcing you to either define it yourself or not use it. Having a const member happens to be one of those conditions, as you can see in the below link under the section quoted,
You really need to revise your code and your notes. The last line above is an assignment. The bob and clone objects have already been created, so that line doesn't involve any constructor. You should also move Nsize out of the class definition -- it doesn't belong there.
It would be a good idea for you to review the chapter in Gaddis that discusses constructors and operator overloads. Here's a short example
C++:
PersonInfo joe; // Calls a default constructor, which you don't have - compiler error
PersonInfo bob("Bob Faraday", 32); // Calls the constructor with two arguments - OK
PersonInfo fred(bob); // Calls the copy constructor - OK
joe = fred; // Calls operator=(), which you now have - OK
You really need to revise your code and your notes. The last line above is an assignment. The bob and clone objects have already been created, so that line doesn't involve any constructor. You should also move Nsize out of the class definition -- it doesn't belong there.
It would be a good idea for you to review the chapter in Gaddis that discusses constructors and operator overloads. Here's a short example
C++:
PersonInfo joe; // Calls a default constructor, which you don't have - compiler error
PersonInfo bob("Bob Faraday", 32); // Calls the constructor with two arguments - OK
PersonInfo fred(bob); // Calls the copy constructor - OK
joe = fred; // Calls operator=(), which you now have - OK
Thanks
That's what I've been doing the last week, revising the constructors, copy constructor and all that. I know it's important. I read through the two chapter again carefully.
That's another thing, I really don't know where to put variables like Nside. What is the rule where to put variables? I know you put in private if you don't want to change it by outside, but what's the difference between putting in public or outside the class definition? How do I know it doesn't belong there. It is more than I should or should not, Compiler sometimes gives error if it is put in the wrong place. I don't recall the book ever talk about this, it's like hit and miss for me!
Thanks for all your help. This C++ really get me on my weakest part...memorize all the rules, functions and all that. There are so so many rules. My memory is really deteriorating now, it's like in test if you call out 3 numbers and want me to repeat it, I might have problem remembering that now. I had test before that I can remember 10+ numbers. I would never past the cognitive test now! So many time you ask whether I read the replies from you guys...I did, just forgot! It's really a struggle. This is so different from electronics. The theory and stuffs in electronics are very difficult to understand, BUT we don't have a lot. Once you understand and practice, you can get good at it over time and not a whole lot to remember. This C++ have so many things to remember, anyone of them are easy, but just have so many. Like I have to keep reminding me to put const in the argument for Copy Constructor and Constructor for the rhs, then the Rule of Three. I spent a bigger part of yesterday struggling on the program that you called out I missed the Assignment. That's in the Rule of Three that I learn the day before and forgot!
It's like Calculus, You can sum up the first two semester in the front two pages and back two pages in most of the Calculus books. Hell, add another two pages, you can put the multi-variables 3rd semester in already. Try putting the essential stuffs of C++ in the first pages of the book, it's going to be a long one. Nothing difficult, just a lot of it. Pointers is one of the subject that doesn't have a lot to remember, but it has the twist and turn that it's difficult to really gets it.
In a way, C++ is good for me, really challenge my memory that I won't get if I keep working on electronics. Those I remember from before and have no problem remember and using them, I can do all the twisting and turning with it even now. But learning a completely new thing is something else. Just hope this brain exercise ( learning C++) is worth my while like doing physical exercise!
That's another thing, I really don't know where to put variables like Nside.
It's not really a variable, as it won't change when the program runs. Things like this are often called parameters (different from function parameters) or named constants. The proper place for it is outside the class, like up at the top of the program.
One style that is used a lot for named constants is ALL CAPS. That makes them really stand out in the code. Aside from this, Nside is not a good name to use, as it seemingly represents the number of sides on some geometric figure. A better choice would be MAX_NAME_LEN or something similar.
yungman said:
But learning a completely new thing is something else. Just hope this brain exercise ( learning C++) is worth my while like doing physical exercise!
Of course it is worth your while. The main reason I teach a class or two a year is to help exercise my brain. That's also why I work the NY Time crossword puzzle every day, as well as post here at PF. These activities help to exercise my brain and keep the neurons working.
#59
yungman
5,741
294
Mark44 said:
It's not really a variable, as it won't change when the program runs. Things like this are often called parameters (different from function parameters) or named constants. The proper place for it is outside the class, like up at the top of the program.
One style that is used a lot for named constants is ALL CAPS. That makes them really stand out in the code. Aside from this, Nside is not a good name to use, as it seemingly represents the number of sides on some geometric figure. A better choice would be MAX_NAME_LEN or something similar.
Of course it is worth your while. The main reason I teach a class or two a year is to help exercise my brain. That's also why I work the NY Time crossword puzzle every day, as well as post here at PF. These activities help to exercise my brain and keep the neurons working.
Thanks
So if it is declared const, I should put in global?
Ha ha, try learning something that you don't know! Like what I am doing, C++ is so much more than Pascal, after like chapter 4, it's all new to me. That's the reason I take a break from electronics. My former company asked me to do a contract for a year and half in 2015, I did not miss a beat working. Then designed two guitar amps and then a few audiophile power amps successfully. Nothing is like learning C++ that I don't know. Electronics to me is more like muscle memory, a lot of it is automatic even thought it's in a different field. Maybe it's like you learning another language, it would be very easy as you already know how programming is.
I hope C++ can shake out more rust from my brain. My English is too bad to even try cross word puzzle.
The proper place for it is outside the class, like up at the top of the program.
I don't agree with that - this constant is used to specify the length of class members that are C-strings so it shouldn't be plluting the global namespace. Namespacing it is one option but probably beyond the current level of expertise (!), otherwise I don't see anything wrong with making it a static const class member.
Edit: on second thoughts as this value is only used at compile time I would make it a macro e.g.