Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

c++ object array declaration

Options
  • 21-11-2008 10:44am
    #1
    Registered Users Posts: 244 ✭✭


    ok say i have a class circle with 3 parameters. i'd declare a variable of type circle - circle c1(a, b, c) i think..

    but how do i declare an array of circles if it takes parameters?


Comments

  • Registered Users Posts: 1,996 ✭✭✭lynchie


    Well without doing it dynamically at runtime.. you can do it as follows

    Circle* myArray[3];

    Circle c1(1,2,3);
    Circle c2(2,3,4);
    Circle c3(4,5,6);

    myArray[0]=&c1;
    myArray[1]=&c2;
    myArray[2]=&c3;


  • Registered Users Posts: 981 ✭✭✭fasty


    That's all well and good until c1, c2 and c3 go out of scope... Make sure you give the Circle class a valid copy contructor and operator= functions (Google this stuff, it's easy and chances are your compiler will generate default versions of these functions for you that'll work fine unless you've got dynamic memory allocation or the like in your Circle class) then...
    Circle myArray[3];
    myArray[0] = Circle(1,2,3);
    myArray[1] = Circle(2,3,4);
    myArray[2] = Circle(4,5,6);
    


  • Registered Users Posts: 5,379 ✭✭✭DublinDilbert


    fasty wrote: »
    Circle myArray[3];
    myArray[0] = Circle(1,2,3);
    myArray[1] = Circle(2,3,4);
    myArray[2] = Circle(4,5,6);
    

    Will that not try call the default constructor, if available upon the declaration Circle myArray[3];

    Its not major as the next 3 calls will assign 3 new static objects to the objects in the array.


    You could also try to create them dynamically:-
    Circle *myArray[3];
    myArray[0] = new Circle(1,2,3);
    myArray[1] = new Circle(2,3,4);
    myArray[2] = new Circle(4,5,6);
    


  • Registered Users Posts: 981 ✭✭✭fasty


    Yeah it would call the default constructor alright!


Advertisement