I'm not understanding Parameterized Constructors in C++

  • Comp Sci
  • Thread starter shivajikobardan
  • Start date
  • Tags
    C++
In summary, the code creates a String object with a given character array, allocates memory for the string, copies the string using strcpy, and then prints the string using the << operator. The s variable is a pointer that stores the address of the first character in the string. The strlen function counts the number of characters in the string until it reaches a null character. The copy constructor creates a copy of the original String object and the change function allows for the modification of the string by deleting the existing string and creating a new one with the given character array.
  • #1
shivajikobardan
674
54
Homework Statement
parameterized constructor in c++
Relevant Equations
none
I am not understanding this code meaning

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:
1682166956024.png
1682166956070.png


1682166956124.png
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?
1682166956197.png
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
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:
Physics news on Phys.org
  • #2
shivajikobardan said:
I imagine a scenario like this:
Your first picture is a reasonable representation of how things relate.

Your second and third pictures show some misunderstanding.
In the 2nd picture, you have *str = "Hello world"; and "Content of 2000H = "Hello world"
Both of these are incorrect.
str contains the address of the first character in that string; namely the letter 'H'.
That address is a byte address that can contain only a single character.

shivajikobardan said:
How can we says strlen(str) finds the length of "Hello World"?
Because str=2000H. We need to have said strlen(*str) instead.
strlen() is used on C-style character strings. strlen(*str) would generate a compile-time error, as strlen() requires the address of a character, not a character. The way strlen() works is that it starts at the address represented by its parameter, and increments an internal count variable as it iterates through the string. It stops when it finds the null character that marks the end of the string.

shivajikobardan said:
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
In your first question above, the picture is reasonably accurate. The new operator allocates an array of length size + 1. The print() method is nothing more than a wrapper around the C++ way of displaying a string. What you probably don't understand is that the stream insertion operator, <<, has many different overloads, one for each type that it works with. If a C-style string is the argument, the insertion operator starts at the first character at the given address, and continues inserting characters into the stream until it hits a null character.
shivajikobardan said:
Again I don't understand how can we just do strcpy(s,str), should not we do strcpy(*s,*str) instead?
Because the C standard library function strcpy() expects its parameters to be of type "pointer to char"; i.e., char *. In your example, *s and *str would be of type char, not char *, so this wouldn't compile.
 
  • #3
Mark44 said:
Your first picture is a reasonable representation of how things relate.

Your second and third pictures show some misunderstanding.
In the 2nd picture, you have *str = "Hello world"; and "Content of 2000H = "Hello world"
Both of these are incorrect.
str contains the address of the first character in that string; namely the letter 'H'.
That address is a byte address that can contain only a single character.strlen() is used on C-style character strings. strlen(*str) would generate a compile-time error, as strlen() requires the address of a character, not a character. The way strlen() works is that it starts at the address represented by its parameter, and increments an internal count variable as it iterates through the string. It stops when it finds the null character that marks the end of the string.In your first question above, the picture is reasonably accurate. The new operator allocates an array of length size + 1. The print() method is nothing more than a wrapper around the C++ way of displaying a string. What you probably don't understand is that the stream insertion operator, <<, has many different overloads, one for each type that it works with. If a C-style string is the argument, the insertion operator starts at the first character at the given address, and continues inserting characters into the stream until it hits a null character.

Because the C standard library function strcpy() expects its parameters to be of type "pointer to char"; i.e., char *. In your example, *s and *str would be of type char, not char *, so this wouldn't compile.
thanks for the detailed explanation.
 

FAQ: I'm not understanding Parameterized Constructors in C++

What is a parameterized constructor in C++?

A parameterized constructor in C++ is a constructor that takes one or more arguments to initialize an object with specific values at the time of its creation. This allows for more flexible and precise initialization of objects compared to default constructors, which do not take any arguments.

How do you define a parameterized constructor in a C++ class?

To define a parameterized constructor in a C++ class, you declare it inside the class definition and then define its body. For example:

class MyClass {public:    int x;    MyClass(int val) { x = val; }};
In this example, MyClass has a parameterized constructor that takes an integer argument and uses it to initialize the member variable x.

Can you have multiple parameterized constructors in a single class?

Yes, you can have multiple parameterized constructors in a single class, a feature known as constructor overloading. Each constructor must have a different parameter list. For example:

class MyClass {public:    int x, y;    MyClass(int val1) { x = val1; y = 0; }    MyClass(int val1, int val2) { x = val1; y = val2; }};
In this example, MyClass has two parameterized constructors with different parameter lists.

What is the difference between a default constructor and a parameterized constructor?

A default constructor is a constructor that takes no arguments and initializes an object with default values. A parameterized constructor, on the other hand, takes one or more arguments to initialize an object with specific values. If no constructors are defined, C++ automatically provides a default constructor. However, if any constructor is defined, including parameterized ones, the default constructor is not provided unless explicitly defined.

How do you call a parameterized constructor in C++?

You call a parameterized constructor when you create an instance of a class by passing the required arguments. For example:

MyClass obj(10); // Calls the parameterized constructor with one argumentMyClass obj2(10, 20); // Calls the parameterized constructor with two arguments
In this example, obj and obj2 are created using different parameterized constructors of the MyClass.

Similar threads

Replies
21
Views
4K
Replies
3
Views
1K
Replies
24
Views
3K
Replies
3
Views
881
Replies
3
Views
2K
Replies
7
Views
2K
Replies
6
Views
19K
Replies
14
Views
4K
Back
Top