+ 1
Can't get expected response. Need your help, guys.
Can't get expected respose from the programm. Apparently I made a mistake in a code, but I do need your help to point on it. The code is following: Header: #pragma once class MyClass { public: MyClass(); ~MyClass(); }; Source: #include "stdafx.h" #include "MyClass.h" #include <iostream> using namespace std; MyClass::MyClass() { cout << "Constructor" << endl; } MyClass::~MyClass() { cout << "Destructor" << endl; } Main: #include "stdafx.h" #include <iostream> #include "MyClass.h" using namespace std; int main() { MyClass obj(); return 0; } The result is empty console, asking me to push any button to continue. I would really appreciate any help.
5 Réponses
+ 4
@fueledbysushis is right, but the reason why is interesting...
When you did MyClass obj(); you were declaring a prototype of a function named 'obj' that will return and instance of MyClass, not an object of MyClass.
But you may wonder why, since this looks a little bit strange! (declaring a prototype inside a function scope - typically we do that at global scope).
But, for example, if you do this:
int main() {
MyClass obj; //This will now work and call MyClass default ctor.
MyClass obj2 = foo(); //Compiler will error on undeclared foo
return 0;
}
MyClass foo() {return MyClass();}
So that does not work, since the foo functoin is declared after main. But if you add this:
int main() {
MyClass obj; //This will now work abd call MyClass default ctor.
MyClass foo(); //foo is declared in function scope!
MyClass obj2 = foo(); //Compiler is now happy!
return 0;
}
And you can see that MyClass foo(); and MyClass obj(); has identical "signatures", so the compiler is unable to deduce which one you mean, and as a rule assumes it to be a function declaration and not an object instantiation.
OTOH, for any non-default constructor, for example like this...
MyClass::MyClass(int x) {
cout << "Constructor: " << x << endl;
}
.. you indeed need to instantiate it like this:
MyClass obj(3);
But here there is no confusion - that statement cannot be a function prototype since there is a literal value, and not a type on the argument.
Incidentally, if you declare the object on the heap with the default ctor the use of parenthesis is optional:
MyClass *p = new MyClass; //Good!
MyClass *p = new MyClass(); //Also good!
0
@fueledbysushis, it worked. Thank you for helping me, but why should I declare it without braces?
0
@Ettienne Gilbert, it was such a detailed explanation. Made me reflecting on this theme from a different angle. It's really helpful. Thanks a lot!
0
@Arthur, you are most welcome! :)