- #1
shivajikobardan
- 674
- 54
- Homework Statement
- parameterized constructor in c++
- Relevant Equations
- none
I am not understanding this code meaning
Q1)
Let's look at the main function.
This invokes this constructor.
I imagine a scenario like this:
How can we says strlen(str) finds the length of "Hello World"?
Because str=2000H. We need to have said strlen(*str) instead.
What's the effect of s= new char[size+1]? Is this the effect?
Again I don't understand how can we just do strcpy(s,str), should not we do strcpy(*s,*str) instead?
Now, we go to str1.print() in main() function.
Here we do
Again as I said above, s is just a pointer and stores the address of first memory location of string. For eg: it is 2000 in third picture.Q2) I have other questions in str2 as well which uses a copy constructor, but I'll ask them in a new post.
A request I'd like to make to mentors would be if possible share some pictures, it doesn't have to look wonderful, any random sketch would help a lot to me. A picture speaks 1000 words and an example speaks 1000 paragraphs. So, figures and examples will be much appreciated.
I'd be glad to see article links to read if there's already someone who has answered these questions.
Code:
#include<iostream>
#include<cstring>
using namespace std;
class String
{
private:
char *s;
int size;
public:
String(const char *str)
{
size=strlen(str);
s=new char[size+1];
strcpy(s,str);
}
~String()
{
delete[] s;
}
String(const String& old_str)
{
size=old_str.size;
s=new char[size+1];
strcpy(s,old_str.s);
}
void print()
{
cout<<s<<endl;
}
void change(const char *str)
{
delete [] s;
size=strlen(str);
s=new char[size+1];
strcpy(s,str);
}
};
int main()
{
String str1("Hello World");
String str2=str1;
str1.print();
str2.print();
str2.change("Namaste");
str1.print();
str2.print();
return 0;
}
Q1)
Let's look at the main function.
Code:
String str1("Hello world");
This invokes this constructor.
Code:
String(const char *str)
{
size=strlen(str);
s=new char[size+1];
strcpy(s,str);
}
I imagine a scenario like this:
Because str=2000H. We need to have said strlen(*str) instead.
What's the effect of s= new char[size+1]? Is this the effect?
Now, we go to str1.print() in main() function.
Here we do
Code:
cout<<s
Again as I said above, s is just a pointer and stores the address of first memory location of string. For eg: it is 2000 in third picture.Q2) I have other questions in str2 as well which uses a copy constructor, but I'll ask them in a new post.
A request I'd like to make to mentors would be if possible share some pictures, it doesn't have to look wonderful, any random sketch would help a lot to me. A picture speaks 1000 words and an example speaks 1000 paragraphs. So, figures and examples will be much appreciated.
I'd be glad to see article links to read if there's already someone who has answered these questions.
Last edited: