Why are default constructors necessary?

All the tutorials I have watched & read on objected oriented programming in C++ tell me to use default constructors in order to initialize all the member variables of a class to their null state. But from a book i'm also learning from, it has an example (which i have also tested and it works) of a class without a default constructor which leads me to question why are default constructors necessary?

An insight would be much appreciated :)
If you don't include any constructors in your class the compiler makes a default constructor for you.
And in debug mode your compiler might make zero values which would make it seem irrelevant. But a release build can be different.

You should implement a default constructor to explicitly assign values to your member variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

class A
{
public:
    int myValue;
    // this class does not have a default constructor!
};

class B
{
public:
    int myValue;
    B()  // the default constructor (default means no-params)
    {
        myValue = 0;
    }

    B(int initialValue)  // here is an "explicit constructor" example
    {
        myValue = initialValue;
    }
};

int main()
{
    A myClassA;
    B myClassB;

    std::cout << "A's value: " << myClassA.myValue << std::endl;
    std::cout << "B's value: " << myClassB.myValue << std::endl;
}


If you were to compile this, and run it; I have no idea what would appear on the first line, but I know for sure that the 2nd line will display the number '0'.

so as you stated:
"use default constructors in order to initialize all the member variables of a class to their null state"
maybe replace the word "null" with default when you read that.
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr376.htm
If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A().
No default constructor is created for a class that has any constant or reference type members.

Default constructor is executed, among other ways, when you write something like:
MyClass foo;//Default constructor called here
Last edited on
Topic archived. No new replies allowed.