For examle there are two sample below arent they same thing
No. In the first one, the only way to create an object of type deneme is to pass it an int. In the second, the only way to create an object of type deneme is with the default constructor that takes no parameters. They're clearly different.
If I saw this in real code, I'd guess that in the first case you wanted to make it impossible to create an object of type deneme without having though carefully about what value to give it - you're making it impossible to create a object with unknown internal data. Can you think of cases where that might be useful? I can.
In the first example you can't change the value of "a", and in the second example you can't get the value of "a" without changing it. More proper to have separate "set" and "get" functions.
A reason for constructors is that it will save coding back in main. If I have a class called Rectangle, which stores the width, height, and area of a rectangle, I don't want to this every time I make a rectangle:
The values of the members and the objects referred to by members are collectively called the state of the object (or simply, its value). A major concern of a class design is to get an object into a well defined state (initialization/construction), to maintain a well defined state as operations are performed, and finally to destroy the object gracefully. The property that makes the state of an object well-defined is called its invariant.
Thus, the purpose of initialization is to put an object into a state for which the invariant holds. Typically, this is done by a constructor. Each operation on a class can assume it will find the invariant true on entry and must leave the invariant true on exit. The destructor finally invalidates the invariant by destroying the object.
- Stroustrup
1 2 3 4 5 6
struct point
{
double x ; // any value is ok for x
double y ; // any value is ok for y
// ...
};
point does not 'need' a constructor - though we may write one (or more) for convenience.
struct time_of_day
{
int hour ; // 0-23
int minute ; // 0-59
int second ; // 0-59
inlinebool valid() const // does the class invariant hold?
{ return hour>=0 && hour<24 && minute>=0 && minute<60 && second>=0 && second<60 ; }
time_of_day( /* ... */ )
{
// whatever
assert( valid() ) ; // the constructor must establish the class invariant
}
void increment()
{
assert( valid() ) ; // the the class invariant holds
// increment time of day
assert( valid() ) ; // the the class invariant still holds
}
// ...
};
time_of_day 'needs' a constructor - it has a non-trivial class invariant.