This question is about object instantiations in C++. There are several ways to instantiate objects both on heap and on stack I am curious to know the subtle differences.
using namespace std;
class Raisin
{
private:
int x;
public:
Raisin():x(3){}
Raisin(int input):x(input){}
void printValue()
{
cout<< "hey my Deliciousness is: " << x <<endl;
}
};
Basically Raisin
is a simple class that I am using for this demonstration:
int main()
{
Raisin * a= new Raisin;
a->printValue();
Raisin * b= new Raisin{};
b->printValue();
Raisin * c= new Raisin();
c->printValue();
Raisin x;
x.printValue();
Raisin y{};
y.printValue();
Raisin z();
z.printValue();
//error: request for member 'printValue' in 'z',
//which is of non-class type 'Raisin()'
Raisin alpha(12);
alpha.printValue();
Raisin omega{12};
omega.printValue();
return 0;
}
I would like to know why Raisin * c
can be instantiated with empty parenthesis, but but Raisin z
cannot be. (Actually Raisin z()
is legal but incorrect)
Also I understand there is a subtle difference between Raisin (2)
and Raisin{2}
. I would appreciate if someone can shed light on the idiosyncrasies.
This line
Raisin z();
Declares a function (with no argument) returning a Raisin object, not a default-constructed Raisin