Because you can do
[code]MyClass m = new MyClass(param1, param2...);[/code]
instead of
[code]MyClass m = new MyClass();
m.param1 = ...;
m.param2 = ...;[/code]
I come from C# so this might be wrong in ++,but through constructor you can initialize readonly variables that later cannot be modified by accessing them with m.param1 = ...
Also in constructor you can put initialization logic so you don't have to later call m.Init() on your class. Easier to manage and debug like that imo.
Different constructors can have different init logic which can come very handy based on input parameters.
Imagine you have a 3d vector class, with construct you simply do
[code]v = new Vector3(1,2,3);[/code]
Without it you have to manually set x, y, and z. That's tedious, adds more code and can quickly fill up code with junk.
oo
There's actually a bit more to it than that.
As he said, constructors are good anytime you need to initialize member variables to certain things.
You can define constructors that take parameters like any other function, and use that to initialize variables. But that's only if you need them to be initialized to a certain thing when they are made.
If you do not define a constructor, one will be synthesized for you. This constructor simply uses each member type's default constructor to define it, be it built-in type or class type (as long as it has one!)
A default constructor is a constructor that takes no arguments.
Remember that you ALWAYS need to define constructors for classes that have type Pointer or Array.
Any further questions may be answered.
Sorry, you need to Log In to post a reply to this thread.