
Originally Posted by
Atomic_Sheep
I don't understand why usually a default or a(more than one) parametrized constructor is included if we can always assign values later anyway or is this another fail safe mechanism used to simplify debugging?
Simple Answer:- To reduce your typing.
for example:-
class MyClass
{
private:
int val;
public:
MyClass() { /*empty*/ }
MyClass( int newVal ) { setVal(newVal); }
void setVal(int newVal) { val = newVal; }
int getVal() { return val; }
}
int main()
{
MyClass obj1;
obj1.setVal(5);
MyClass obj2(5);
}
class MyClass
{
private:
int val;
public:
MyClass() { /*empty*/ }
MyClass( int newVal ) { setVal(newVal); }
void setVal(int newVal) { val = newVal; }
int getVal() { return val; }
}
int main()
{
MyClass obj1;
obj1.setVal(5);
MyClass obj2(5);
}
To copy to clipboard, switch view to plain text mode
as you see initializing obj1 requires two lines of code where as obj2 only requires 1 line. Consider the case where you have to create 50 objects. So you would be writing a lot of code and lot of bugs.
Complicated Answer:- It reduces code duplication, The object is assumed to be usable after its creation. You dont have to document the class like "Make sure u call setVal() at least once before calling getVal() otherwise the returned value is garbage.". And many others benefits.
Bookmarks