While defining the car Class, Bhaiya wrote a function,
car(string n, int x, int y)
{
car-name=n;
this->x=x;
this->y=y;
}
Que1) why didn’t we write this->car_name=n instead of just writing car_name=n;
Que2) For taking the names and coordinates of the car, why did we write temp(name,x,y), I think we should have used car(name,x,y) because we have defined this function inside the car class.
Please explain in detail because I am an average guy!!
Car sorting problem
Hello @Tiwary725,
-
You can use this-> to access the data members but it is not a mandatory representation of accessing data members.
You can access them directly with their name inside the class body.
So, when we need to use this->?
when the name of the data member and the parameter of the function has same name.
Thus, to uniquely identify the data member we use this->, as is done in the case of x and y. -
car(name,x,y) is a constructor and its primary purpose is to initialize the data members as soon as an object is created. Thus, we are not using it.
temp(name,x,y) will take inputs and then assign those values to the data members.
Hope, this would help.
Give a like if you are satisfied.
Why didn’t we use car(name,x,y) instead of temp(name,x,y) ?
Hello @Tiwary7,
But, car() function function would be called only once for an object and that is at the time when you would declare an object.
In future codes you might required to take inputs at different section of the code for the same object then car() won’t help.
You might require a separate function like temp().
we should have used car(name,x,y) after accepting the values of name, x and y
I am sorry but I couldn’t understand anything
Yes @Tiwary725 ,
you can do that but every time you would do this, it will call an implicit copy constructor.
reason:
car(name,x,y) will create a new object and its content will be copied.
You can refer to the following code:
please explain it properly, I can’t get your logic behind this
-
When you call car(name,x,y).
-
When you assign the value of the data members of one object to another using = sign the compiler call the implicit copy constructor to perform the copy operation.
You have not studied constructors yet, then I would suggest you read this again after watching that.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.