Can someone explain me where I can use constructors. It doesn't make me a sence.
5 replies to this topic
#1
Posted 09 November 2011 - 06:23 AM
|
|
|
#2
Posted 10 November 2011 - 08:41 PM
Well, basically constructor is a function that executed when you create an instance of some class. So if you need to perform some operations when object is created - you can use constructor.
#3
Posted 11 November 2011 - 08:48 AM
but constructors does not return any value so what kind of operation i could use calling constructor?
#4
Posted 12 November 2011 - 12:18 AM
The most common example of calling constructor with parameters to set some private class fields to certain initial values:
So as you can see in the example above you cannot directly access car's maxSpeed property, but you can set it once when the object is created.
About returning a value by constructor. Basically we can say that it always returns an instance of it's class :) Not exactly, but it was the easiest way of understanding for me.
By the way, you can read some articles about the basics of the OOP to learn more about constructors / destructors. The main principles are the same for c# or any other object-oriented language..
class Car
{
private int maxSpeed = 0;
private int currentSpeed = 0;
public Car(int maxSpeed)
{
this.maxSpeed = maxSpeed;
}
}
static void Main(...)
{
Car slowCar = new Car(150);
Car fastCar = new Car(300);
}
So as you can see in the example above you cannot directly access car's maxSpeed property, but you can set it once when the object is created.
About returning a value by constructor. Basically we can say that it always returns an instance of it's class :) Not exactly, but it was the easiest way of understanding for me.
By the way, you can read some articles about the basics of the OOP to learn more about constructors / destructors. The main principles are the same for c# or any other object-oriented language..
#5
Posted 12 November 2011 - 03:24 PM
i have found some tutorial for constructors and i get it but isn't it more readable and more easy if you declare 2 variables in Main for slowCar and fastCar?
#6
Posted 12 November 2011 - 05:18 PM
No, cause that variables in Main will not be the class filelds, so they can't be used inside the class, so they don't make any sense for it :)
It'll require too much typing to give a comprehensive description, I think you should just start coding using the OOP and then you get it quickly.
It'll require too much typing to give a comprehensive description, I think you should just start coding using the OOP and then you get it quickly.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









