constructor

what is importance of one argument constructor with example?
there are three types of constructors ('ctor' for short):
1. Default Ctor
2. Paramerized Ctor
3. Copy Ctor

one argumnent ctor looks like this:
(suppose class name is "Student")
Student(int rollno=24)
{
}



this initializes rollno with the value 24
Student(int rollno=24)

I don't think that having a default value parameter in your constructor is very good practice. It's a little bit messy and almost never desirable, for the whole point of arguments in a constructor is to pass values in.

there are three types of constructors

There are actually more. Namely, move constructors and conversion constructors. :)

To answer OPs question, I don't really think that having specifically one parameter is of much importance. However, here is a different example of how it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MyClass
{
public:
    MyClass(int arg)
        : myVar(arg) // initialization list
    {
    }

    int myVar; // member variable
};

int main()
{
    MyClass obj(65); // pass a single integer into the object

    cout << "myVar = " << obj.myVar << endl;
    return 0;
}


This code creates a class called MyClass with a constructor with a single argument. Whenever I create my class object and pass my value as an argument, the constructor uses what is called a "constructor initialization list" (which is the part following the colon in the code) to set the classes member variable, called myVar, to the value passed into the class.

The output of this program will be:
myVar = 65


I don't know if this is what you were looking for, but your question was extremely broad.
Last edited on
Topic archived. No new replies allowed.