Hi there,

I have read that when we create object of a class, its default constructor is automatically called and default constructor assigns default values to variables e.g. to int it assigns 0 and to float it assigns 0.0 ...

But I have write a program in which I have declare different types of variables and did not assign values to them. When I print their values, it still printing garbage values not default values.

Please anyone tell me why is this happening. I just want to learn the concept of default constructor. The program is as follows. Thanks !

#include <iostream>

using namespace std;

class CheckGarbage
{
    private:
        int rollNo;
        float cgpa;
        char* name;

    public:

        void checkValue()
        {
            cout<<"Roll no : " <<rollNo <<endl;
            cout<<"CGPA : " <<cgpa <<endl;
            cout<<"name : " <<name <<endl;
        }
};

int main()
{

    CheckGarbage c;
    c.checkValue();

    return 0;
}

In C++, an unimplemented default constructor does nothing. If you declare and implement the default constructor, you can:

class CheckGarbage
{
private:
    int rollNo;
    float cgpa;
    char* name;
public:
    CheckGarbage()
    {
        rollNo = 0;
        cgpa = 0;
        name = NULL;
    }
    void checkValue()
    {
        cout<<"Roll no : " <<rollNo <<endl;
        cout<<"CGPA : " <<cgpa <<endl;
        cout<<"name : " <<name <<endl;
    }
};

There isn't really an idea of a default value for particular data types in C++, like in some other langauges. What you may be actually referring to, is the default value of a parameter, like so:

CheckGarbage(int r = 0, float c = 0, n = NULL)
{
    rollNo = r;
    cgpa = c;
    name = n;
}

You can read more on them here or here. A constructor with default values for all parameters, takes on the role of the default constructor.

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.