Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Constructors - Odd Doubt

I'm reading about constructors,

When an object is instantiated for a class, c'tors (if explicitly written or a default one) are the starting points for execution. My doubts are

  • is a c'tor more like the main() in C
  • Yes i understand the point that you can set all the default values using c'tor. I can also emulate the behavior by writing a custom method. Then why a c'tor?

Example:

//The code below is written in C#.
public class Manipulate
    {
        public static int Main(string[] args) {
            Provide provide = new Provide();
            provide.Number(8);
            provide.Square();
            Console.ReadKey();
            return 0;
        }
    }   

 public class Provide {
        uint num;
        public void Number(uint number)
        {
            num = number;
        }
        public void Square()
        {
            num *= num;
            Console.WriteLine("{0}", num);
        }
    }

Am learning to program independently, so I'm depending on programming communities, can you also suggest me a good OOP's resource to get a better understanding. If am off topic please excuse me.

like image 308
Chaitanya Avatar asked Jun 25 '10 03:06

Chaitanya


1 Answers

Head First OOA&D will be a good start.

Dont you feel calling a function for setting each and every member variable of your class is a bit overhead.

With a constructor you can initialize all your member variables at one go. Isnt this reason enough for you to have constructors.

like image 62
ckv Avatar answered Sep 23 '22 13:09

ckv