trouble in understanding const object

  • Thread starter subramanian100in
  • Start date
S

subramanian100in

Consider the following program named x.cpp:
#include <cstdlib>

using namespace std;

class Test
{
public:
Test();
};

Test::Test()
{
}

int main()
{
const Test x;

return EXIT_SUCCESS;
}

This program compiles fine with g++3.4.3 as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp

Now consider the following program y.cpp:
#include <cstdlib>

using namespace std;

class Test
{
};

int main()
{
const Test obj;

return EXIT_SUCCESS;
}

When I compile this program as
g++ -std=c++98 -pedantic -Wall -Wextra y.cpp
I get the following compilation error:
y.cpp: In function `int main()':
y.cpp:11: error: uninitialized const `obj'
y.cpp:11: warning: unused variable 'obj'

In x.cpp, the default ctor supplied by the class Test is used.
Why doesn't the compiler-supplied default ctor not used in y.cpp ?

Why do I get compilation error for y.cpp ?

Kindly explain.

Thanks
V.Subramanian
 
A

Alf P. Steinbach

* (e-mail address removed), India:
Consider the following program named x.cpp:
#include <cstdlib>

using namespace std;

class Test
{
public:
Test();
};

Test::Test()
{
}

int main()
{
const Test x;

return EXIT_SUCCESS;
}

This program compiles fine with g++3.4.3 as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp

Now consider the following program y.cpp:
#include <cstdlib>

using namespace std;

class Test
{
};

int main()
{
const Test obj;

return EXIT_SUCCESS;
}

When I compile this program as
g++ -std=c++98 -pedantic -Wall -Wextra y.cpp
I get the following compilation error:
y.cpp: In function `int main()':
y.cpp:11: error: uninitialized const `obj'
y.cpp:11: warning: unused variable 'obj'

In x.cpp, the default ctor supplied by the class Test is used.
Why doesn't the compiler-supplied default ctor not used in y.cpp ?

Why do I get compilation error for y.cpp ?

Kindly explain.

Thanks
V.Subramanian

Any constant must have a programmer-defined value.

Relying on a compiler is not enough.


Cheers & hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top