My initial thoughts on the default constructor are that it was called automatically. From what I can see, it seems that this is so but a constructor called automatically doesn't initialize int or char variables for exampe, to Zero as I originally thought. It appears that they initialize the variable with a garbage value or something associated with the memory location.

**Is it true that the default constructor (if you don't provide a constructor yourself) is called automatically though does not initialize the class variables to any meaningful value? ** I initially thought that it would initialize class variables to zero but it seems that I am wrong on that. It could be a floor in my inderstanding. My code below provides three garbage values for the output if I don't initialize them.

#include <iostream>
#include <cstdlib>

using namespace std;

class test
{
public:

    char a,b,c;

  char testfunct(char d, char e, char f)
    {
        a = d;
        b = e;
        c = f;
    }
};



int main()
{
test classtest;

cout << classtest.a << "\n";
cout << classtest.b << "\n";
cout << classtest.c << "\n";

system("pause>nul");
}

If undeclared/unimplemented, C++ will create default base constructor (no arguments), copy constructor, destructor, and assignment operator. The base constructor will do no initialization of variables whatsoever. The copy constructor will do a bit-wise copy of the copied data (member variables), as will the assignment operator. Often these are not safe. In any case, you should always create your own default constructor, and initialize all member variables. Example:

class foo
{
private:
    int a;
    int b;
    int c;
public:
    foo() : a(0), b(0), c(-1) {}
};

Thanks rubberman. That makes sense. For some reason I always thought the default constructor would initialize values to zero (in the case of ints for example).

The reason this is confusing is I watched a tutorial recently where the instructor showed us how to create a default constructor and initialized everything to zero in the function body so I thought if it's default, wouldn't it do this automatically. Maybe the instructor shouldn't have called it the default constructor, but a constructor which initializes everything to zero.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.