Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ default Constructor not being called [duplicate]

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();
}
like image 939
MichelleJS Avatar asked Oct 27 '13 07:10

MichelleJS


People also ask

Why is my copy constructor not being called?

It's because of copy elision optimization by the compiler. Adding -fno-elide-constructors option to g++ while compiling will disable that optimization.

Can constructor be called twice?

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.

Does copy constructor call default constructor?

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.

How many times copy constructor is called?

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.


2 Answers

 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;
like image 143
Alok Save Avatar answered Oct 12 '22 08:10

Alok Save


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
like image 24
juanchopanza Avatar answered Oct 12 '22 08:10

juanchopanza