2

I wonder how to initialize each object in a dynamically allocated array with some arguments.

I'm aware of that how to initialize all objects in a dynamically allocated array with a default constructor.

For example, Suppose there is a class named Circle, which has a member variable named radius. I know

Circle *arr=new Circle[5]

means a Circle object is constructed by the default constructor.

But how can I do some work like this? (though this doesn't work.)

Circle *arr=new Circle[5](10)

Following is the whole code that you can refer to.

#include <iostream>
using namespace std;
class Circle
{
private:
    int radius;
public:
    Circle(int r)
    {
        cout << "radius : " << r << endl;
        this->radius = r;
    }
    Circle()
    {
        cout << "radius : 0" << endl;
        this->radius = 0;
    }

    ~Circle()
    {
        cout << "deleted" << endl;
    }
};
int main()
{
    Circle *arr = new Circle[5];
    // Here, What I want is something like this
    // Circle *arr = new Circle[5](10) //10 would be an argument meaning radius

    delete[] arr;
    system("pause");
}
7
  • 6
    Use a std::vector. Commented Apr 16, 2019 at 13:31
  • 2
    std::vector<Circle> arr(5, 10) will do the job, without the need for explicitly using dynamic memory allocation. Commented Apr 16, 2019 at 13:33
  • Thank you. I knew vector but just wondered if array could implement those work. Thank you very much!! Commented Apr 16, 2019 at 13:40
  • why dont you want to use the default contructor? The default constructor is the contructor that default constructs an object, so if you want default constructed objects to have some default values thats the place to put them Commented Apr 16, 2019 at 13:41
  • I worried about some cases when users input data. Commented Apr 16, 2019 at 13:44

2 Answers 2

3

you can use std::vector.

If you still want to use arrays, you can use

Circle *arr = new Circle[5]{10}; which initializes first radius to 10 and use default for others.

Sample output will be:

radius : 10
radius : 0
radius : 0
radius : 0
radius : 0
deleted
deleted
deleted
deleted
deleted 

If you want a single line solution you can use this dirty line:

Circle *arr = new Circle[5]{10,10,10,10,10};

Sign up to request clarification or add additional context in comments.

Comments

3

I solved this problem.

I wondered if I can implement those work by using arrays.

But I figured out I can make it by using std::vector

vector<Circle> arr(num,Circle(radius))

and then, constructor Circle(int r) is invoked only once

copy constructor Circle(Circle& c) is invoked multiple times.

Thank you!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.