#include<iostream>
using namespace std;
class test {
        public:
                void display() const {
                        cout<<"Hai Here in class"<<endl;
                        }
        };
int main() {
        const test b;
        b.display();
        }

When I execute the above code I got an error saying "uninitialized const b". But if I provide a default constructor it will compile without any error.
My question is, doesn't compiler provide the default constructor when we declare an object of type const? Any help is much appreciated.
Thanks in advance.

My question is, doesn't compiler provide the default constructor when we declare an object of type const?

There is no such limitation. The above code compiles under Visual Studio 2003.

PS.
But if you have a data member in the class, things should be different. That is because if you are not initializing data while creating the object, you can't change any of it later.

There is no such limitation. The above code compiles under Visual Studio 2003.

Thank you very much for your quick reply.
When I tried to compile under g++, it gave the above said error. Could you please clarify me with respect to g++. Thanks

Maybe Visual C++ allows objects of classes without data members to be declared const even when a constructor is not defined. Because there are no data members, there is no data to be initialized so there is nothing wrong with it. But VC gives a warning when objects of classes with data members are declared const without a proper constructor.

On the other hand g++ apparently doesnt give any room whether the class has data members or not.

I would quote the apporoprite portion of the C++ standard to find what it has to say about this, but I am a bit pressed for time.

Maybe Visual C++ allows objects of classes without data members to be declared const even when a constructor is not defined. Because there are no data members, there is no data to be initialized so there is nothing wrong with it. But VC gives a warning when objects of classes with data members are declared const without a proper constructor.

On the other hand g++ apparently doesnt give any room whether the class has data members or not.

I would quote the apporoprite portion of the C++ standard to find what it has to say about this, but I am a bit pressed for time.

Thanks a lot for your kind reply.

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.