code understanding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "stdafx.h"
#include <iostream>

class T 
{
public:
	T() { std::cout<<"T()"<<std::endl; }
	T(int) { std::cout<<"T(int)"<<std::endl; }
};

int a, x;

int main()
{
	T(a);       //1
	T b();      //2
	T c(T(x));
	return 0;
}


here what does the lin1-2 1nd line-2 specify (commented with nos) ??
#1) Creates a temporary, nameless object of type 'T', then discards it.

#2) This is a function prototype for a function named 'b'. The function returns a T and takes no parameters. Note it does NOT create a T object. 'b' is a function name, not an object name.
Does the temporary nameless object is same as anonymous object.

If yes why the p[parametrized constructor is not called.
Does the temporary nameless object is same as anonymous object.


I guess. I kind of suck with terminology.

If yes why the p[parametrized constructor is not called.


AFAIK, it should be getting called.

I'll test this when I get home. Can't test it at work.
Looks like you're trying to understand how overloaded constructors are called from client code. Like Disch said, 1) lacks an identifier, 2) defines a function prototype in main() and the last statement also defines a prototype that casts it's parameter to type T, as if you had written
T c(static_cast<T>(x));

To call the default constructor with no parameters you'll need a statement in main like
T defaultCtor;

Here's my version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// #include "stdafx.h" why do you need this?
#include <iostream>
using std::cout;  // explicity declare the scope of our identifiers from the stdlib for portability
using std::endl;

class T 
{
public:
	T() { std::cout<<"T()"<<std::endl; }
	T(int) { std::cout<<"T(int)"<<std::endl; }
};

int main()
{
	T(0);       //1 
	T b;      //2
	// T c(T(x));    this is nonsense
	return 0;
}
Last edited on
THANX
actually
1) lacks an identifier
doesn't appear to be quite the whole story. I think T(a) is just attempting to cast the global variable a to type T, which results in a temporary new object of type T being created with the default constructor. Using T(0) or with any other constant integer type can't be treated as a cast, so it's treated as a declaration.

EDIT: also using T(0); the object created will remain in memory until the closing brace of main() and it goes out of scope, but it will be inaccesible due to a lack of handle. T(a) on the other hand, being a simple cast with no assignment or declaration, creates a temporary T object that is destroyed at the end of the statement.
Last edited on
Topic archived. No new replies allowed.