News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

c+= array tips - Another variation on initializing object arrays

Started by ben2ong2, October 06, 2006, 05:54:23 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

PROBLEM: You are not allowed to view links. Register or Login (S. Chalavadi)

Can anyone help me in this

class Y {
  int j;
  X tempx[100]; // array of classs X
public :
  Y(){}
  Y(int t) { j=t;}
};


Now how can i initialize array tempx ,with  a  specific constructor
X(char *, int),  in class Y (again tempx is array of class
X) .Can any one suggest me how i should write a constructor in the container
class Y that takes care of this initialization.


RESPONSE: You are not allowed to view links. Register or Login (Fergus James HENDERSON), 16 Jun 93

You can use placement operator new and explicit calls to delete to do this.
Eg.
   #include <new.h>

   Y::Y() {
      // at this stage, tempx will have been initialized
      // using the default constructor. If we want to
      // reinitialize it, we need to destroy the old values first:

      for (int i = 0; i < 100; i++) {
         tempx.~X();
      }

      // now initialize using different constructor
      for (i = 0; i < 100; i++) {
         new(tempx) X("argument to constructor", 1);
      }
   }
You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login