- c Object array initialization without default constructor
- #include <iostream>
- class Car
- {
- private:
- Car(){};
- int _no;
- public:
- Car(int no)
- {
- _no=no;
- }
- void printNo()
- {
- std::cout<<_no<<std::endl;
- }
- };
- void printCarNumbers(Car *cars, int length)
- {
- for(int i = 0; i<length;i++)
- std::cout<<cars[i].printNo();
- }
- int main()
- {
- int userInput = 10;
- Car *mycars = new Car[userInput];
- for(int i =0;i < userInput;i++)
- mycars[i]=new Car[i+1];
- printCarNumbers(mycars,userInput);
- return 0;
- }
- cartest.cpp: In function ‘int main()’:
- cartest.cpp:5: error: ‘Car::Car()’ is private
- cartest.cpp:21: error: within this context
- #include <iostream>
- #include <vector>
- class Car
- {
- private:
- Car(); // if you don't use it, you can just declare it to make it private
- int _no;
- public:
- Car(int no) :
- _no(no)
- {
- // use an initialization list to initialize members,
- // not the constructor body to assign them
- }
- void printNo()
- {
- // use whitespace, itmakesthingseasiertoread
- std::cout << _no << std::endl;
- }
- };
- int main()
- {
- int userInput = 10;
- // first method: userInput copies of Car(5)
- std::vector<Car> mycars(userInput, Car(5));
- // second method:
- std::vector<Car> mycars; // empty
- mycars.reserve(userInput); // optional: reserve the memory upfront
- for (int i = 0; i < userInput; ++i)
- mycars.push_back(Car(i)); // ith element is a copy of this
- // return 0 is implicit on main's with no return statement,
- // useful for snippets and short code samples
- }
- void printCarNumbers(Car *cars, int length)
- {
- for(int i = 0; i < length; i++) // whitespace! :)
- std::cout << cars[i].printNo();
- }
- int main()
- {
- // ...
- printCarNumbers(&mycars[0], mycars.size());
- }
- class Car {
- int _no;
- public:
- Car( int no ) :_no( no ) {
- }
- };
- int main() {
- void* raw_memory = operator new[]( NUM_CARS * sizeof( Car ) );
- Car* ptr = static_cast<Car*>( raw_memory );
- for( int i = 0; i < NUM_CARS; ++i ) {
- new( &ptr[i] )Car( i );
- }
- // destruct in inverse order
- for( int i = NUM_CARS - 1; i >= 0; --i ) {
- ptr[i].~Car();
- }
- operator delete[]( raw_memory );
- return 0;
- }
- static Car* Car::CreateCarArray(int dimensions)
- #define DEFAULT_CAR_INIT 0
- Car::Car(int _no=DEFAULT_CAR_INIT);
- Car *c = (Car*) malloc(sizeof(Car) *userInput);
- Car** mycars = new Car*[userInput];
- for (int i=0; i<userInput; i++){
- mycars[i] = new Car(...);
- }
- ...
- for (int i=0; i<userInput; i++){
- delete mycars[i];
- }
- delete [] mycars;
- static Car* makeArray(int length){
- return new Car[length];
- }
- Car* createCars(unsigned number)
- {
- if (number == 0 )
- return 0;
- Car* cars = reinterpret_cast<Car*>(new char[sizeof(Car)* number]);
- for(unsigned carId = 0;
- carId != number;
- ++carId)
- {
- new(cars+carId) Car(carId);
- }
- return cars;
- }