I am very new to c++ so forgive me if I have overlooked something simple. I have a class Circle:
class Circle: public Shape{
protected:
//string name;
Point focus;
float radius;
private:
public:
virtual void calculateArea();
virtual void calculatePerimeter();
Circle();
Circle(Point p, float r);
};
I have two constructors, one of which is the default which I have overloaded:
Circle::Circle()
{
Point p(1,1);
focus = p;
radius = 10;
name = "Circle";
calculatePerimeter();
calculateArea();
cout<<"default circle"<<endl;
}
Circle::Circle(Point p, float r)
{
focus = p;
radius = r;
name = "Circle";
calculatePerimeter();
calculateArea();
}
In my main I try to create two circles one using the each constructor, however the Circle being created with Circle() never gets created. I cannot for the life of me figure out why? There are no error messages or anything.
int main{
Circle circle(a, 3.3);
Circle c2();
}
It's because of copy elision optimization by the compiler. Adding -fno-elide-constructors option to g++ while compiling will disable that optimization.
A constructor is called only once per object instance. Although, you may choose to call the constructor within the same class. You will have to call it with new key word. This will essentially create a new object instance and the constructor would be invoked by new instance.
The answer is No. The creation of the object memory is done via the new instruction. Copy constructor is then in charge of the actual copying (relevant only when it's not a shallow copy, obviously). You can, if you want, explicitly call a different constructor prior to the copy constructor execution.
And there are 4 calls to copy constructor in f function. 1) u is passed by value. 2) v is copy-initialized from u . 3) w is copy-initialized from v . 4) w is copied on return.
Circle c2();
Does not create an object, it declares a function by name c2
which takes no argument and returns a Circle
object. If you want to create a object just use:
Circle c2;
This here is not an instantiation, but a function declaration:
// parameter-less function c2, returns a Circle.
Circle c2();
You need
Circle c2;
or
Circle c2{}; // requires c++11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With