Because
1) constructors often do more than just initializing one member, which would cause a lot of code duplication.
2) you could forget to initialize one or more members in some cases.
3) when the way an object is initialized gets changed, you don't have to spend days to hunt down hundreds or thousands of places where that kind of object is created in order to fix the initialization.
4) you don't have access to private/protected members from the outside.
@Vlad, all I wouold need to do is put int m_nPages = 0 and remove Book(), no?
@Athar, Thanks. I've realized it's helpful for code duplication and overloading also makes sense. It kinda just clicked - most of the time I've been shown constructors they haven't actually called anything they always just set variables - I don't really see any reason to use a constructor to do nothing but set a variable but I suppose there are some reasons and I never considered using them to call functions, which seems obvious now.
@Hungry Man, all I wouold need to do is put int m_nPages = 0 and remove Book(), no?
You may do that. But not alll classes so simple. Even if a class has all memners public it is better to use a constructor.
Consider the simple example.
1 2 3 4 5
struct Point
{
int x;
int y;
};
In your program you can write
1 2 3 4
Point p;
p.x = 10;
p.y = 20;
But it would be more better to write
Point p( 10, 20 );
if you would have a constructor. Moreovver you could suppose that the statement
Point p;
means that p.x and p.y is assigned 0. Without a default constructor nobody can assume that after this statement p.x and p.y are assigned 0. So he would write
1 2
Point p;
p.x = 0; p.y = 0;
It is very inconvinient.
The better decision is to have two constructors
1 2 3 4 5 6 7
struct Point
{
Point() : x( 0 ), y( 0 ) {}
Point( int x, int y ) : x( x ), y( y ) {}
int x;
int y;
};
And I even do not mention more complex classes with more serious logic during their object initializations.
Setting variables in a constructor is just good design. If you think about, a class is a template of sorts to represent something. What if you want different objects created from this class? Would you really all your data members pre set? This wouldn't allow for any differentiation, unless you wanna call a bunch of getter and setter functions. Or directly change all the members. Constructors are just used to set up an object to be more specific
> But it would be more better to write Point p( 10, 20 );
In what way is it any better than writing Point p { 10, 20 } ;
> What if you want different objects created from this class?
It would still be a very good idea to have default initialization of objects if possible. That you want many different objects of type std::string does not imply that having a default constructor for std::string is a bad idea.