Reputation: 188
Coming from the Java and C# world, I always like to use
someclass a = someclass();
instead of
someclass a();
to initalize a class variable in C++. However, my compiler sometimes complain
Error C2280: Attempting to reference a deleted function
Is there any difference between them? Which one is better?
Upvotes: 5
Views: 1590
Reputation: 72
Dear Friend in C++ user creates the object as follows
classname objectname;
#include<iostream>
using namespace std;
class demo
{
public:
void print()
{
cout<<"Demo class";
}
};
int main()
{
demo d;
d.print();
return 0;
}
OUTPUT Demo class
using pointer object
#include<iostream>
using namespace std;
class demo
{
public:
void print()
{
cout<<"Demo class using pointer object";
}
};
int main()
{
demo *d = new demo();
d->print();
return 0;
}
OUTPUT Demo class using pointer object
In java, garbage collection is done automatically. I hope that you understand concept.
Upvotes: -2
Reputation: 3849
Is there any difference between them?
A big one: someclass a();
is declaring a function!
And someclass a = someclass();
, before C++17's copy ellision, requires the class to be movable, which is probably not the case here as you get the error Attempting to reference a deleted function
.
Which one is better?
None. Use instead:
someclass a;
or
someclass a{}; // C++11
Both will call default constructor.
Upvotes: 9