why wont instance of class call twice?

Aug 8, 2013 at 8:25pm
this program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "iostream"

class cTest
{
public:
	cTest(){
		std::cout << "test" << std::endl;
	}
};

void main(){
	cTest qTest;
	qTest;
	qTest;
	system("pause");
}


returns

test
press any key to continue...


when it seems to me that it should return

test
test
press any key to continue...


any idea why?

also, in case its relevant, im using visual studio express 2012 for windows desktop.
Last edited on Aug 8, 2013 at 8:27pm
Aug 8, 2013 at 8:35pm
The object of type cTest is created only once in the statement

cTest qTest;

So the constructor is called also only once.
Aug 8, 2013 at 8:35pm
cTest qTest; -- this creates a new object called "qTest", using default initialization. Default initialization calls the default constructor, which prints "test".

qTest; this does nothing. (formally, this is a discarded-value lvalue expression)

If you fix the return type of main (it must return int) so that you can compile this on other C++ compilers, you will see most of them complain:
test.cc:13:2: warning: expression result unused [-Wunused-value]
        qTest;
        ^~~~~
test.cc:14:2: warning: expression result unused [-Wunused-value]
        qTest;
        ^~~~~


test.cc:13:7: warning: statement has no effect [-Wunused-value]
test.cc:14:7: warning: statement has no effect [-Wunused-value]


"test.cc", line 13.9: 1540-5337 (I) Null statement.
"test.cc", line 14.9: 1540-5337 (I) Null statement.


Aug 8, 2013 at 8:43pm
qTest; this does nothing


well that would explain it!

thanks
Last edited on Aug 8, 2013 at 8:44pm
Topic archived. No new replies allowed.