Jump to content

Constructors and destructors

- - - - -

  • Please log in to reply
5 replies to this topic

#1
Tonchi

Tonchi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 471 posts
  • Location:Varaždin
  • Programming Language:C, C++, C#
Can someone explain me where I can use constructors. It doesn't make me a sence.

#2
taburetka

taburetka

    Newbie

  • Members
  • PipPip
  • 11 posts
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
Tonchi

Tonchi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 471 posts
  • Location:Varaždin
  • Programming Language:C, C++, C#
but constructors does not return any value so what kind of operation i could use calling constructor?

#4
taburetka

taburetka

    Newbie

  • Members
  • PipPip
  • 11 posts
The most common example of calling constructor with parameters to set some private class fields to certain initial values:

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
Tonchi

Tonchi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 471 posts
  • Location:Varaždin
  • Programming Language:C, C++, C#
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
taburetka

taburetka

    Newbie

  • Members
  • PipPip
  • 11 posts
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.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users