in c++, whats the difference between writing something like
myclass myobject();
//and
myclass myobject;
also i'm new to stack overflow so if i'm doing something wrong just tell me.
in c++, whats the difference between writing something like
myclass myobject();
//and
myclass myobject;
also i'm new to stack overflow so if i'm doing something wrong just tell me.
When you write:
myclass myobject();
You may think you're creating a new object of type myclass
, but you actually declared a function called myobject
, that takes no parameters, and has a return-type of myclass
.
If you want to see that for sure, check this code:
#include <stdio.h>
#include <iostream>
using namespace std;
class myclass
{ public: int ReturnFive() { return 5; } };
int main(void) {
myclass myObjectA;
myclass myObjectB(); // Does NOT declare an object
cout << myObjectA.ReturnFive() << endl; // Uses ObjectA
cout << myObjectB.ReturnFive() << endl; // Causes a compiler error!
return 0;
}
prog.cpp: In function ‘int main()’:
prog.cpp:18:23: error: request for member ‘ReturnFive’ in ‘myObjectB’, which is of non-class type ‘myclass()’
cout << myObjectB.ReturnFive() << endl;
^~~~~~~~~~
The difference is same as,
int a;
and int a();
I am pretty sure that you understand now. Just for the sake of answer, I am explaining it below.
int a; // -> a is a variable of type int
int a(); // -> a is a function returning int with void paramters