4

I am trying to understand how to create multiple objects(20 in the current case) and pass parameter to the constructor as shown in the comments of the code. Unfortunately, I cannot pass parameters as well as have an array of objects at the same time.

I tried this as well to create the object convector con(100,200, construct(20)); but it didn't seem to give the desired result

#include <iostream>

class construct { 
public: 
    int a, b; 

    // Default Constructor 
    construct(int x1,int x2) 
    { 
         a = x1; 
         b = x2; 
    } 
    int getX1(){
        return a;
    }
    int getX2(){
        return b;
    }
};  
int main(){
    int p,q;
    construct* con = new construct[20](100,200);

for (unsigned int i = 0; i < 20; i++) {
    p=con[i]->getX1();
        q=con[i]->getX2();
        printf("%d %d \n",p,q);
    }
    delete con;
    return 1;
}

Expected result would be 20 objects created.

3
  • 5
    Any reason you can't use std::vector? Commented Apr 23, 2019 at 6:11
  • You should be using delete[] con to deallocate. std::vector is much easier to use. Commented Apr 23, 2019 at 6:13
  • 1
    Any reason for using printf instead of std::cout too? Commented Apr 23, 2019 at 6:16

2 Answers 2

4

Just use std::vector. Seriously, there's no reason not to.

std::vector<construct> con(20, {100, 200});
Sign up to request clarification or add additional context in comments.

2 Comments

Upeed. Inb4 the OP comments with "my teacher at my university forbade the use of the standard library"
@StoryTeller It really is unfortunate that some people have that attitude
-1

Yeah, for this you are likely to need placement new sadly (or use std::vector, and pass a newly constructed object as the second argument).

// call global new (effectively malloc, and will leave objects uninitialised)
construct* con = (construct*)::operator new (sizeof(construct) * 20);

// now call the ctor on each element using placement new
for(int i = 0; i < 20; ++i)
  new (con + i) construct(100, 200);

2 Comments

You're encouraging the use of raw memory management facilities
I did specify in my answer that using std::vector would be an option, but that isn't an answer to the actual question asked. The OP's question is about new. It's kinda hard to answer a question about raw memory management facilities, without you know, mentioning the raw memory management facilities.

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.