jeudi 13 août 2015

pointer to class objects initialization with class constructor?

// pointer to classes example
// runs with no problem
#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};


int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << '\n';
  cout << "*foo's area: " << foo->area() << '\n';
  cout << "*bar's area: " << bar->area() << '\n';
  cout << "baz[0]'s area:" << baz[0].area() << '\n';
  cout << "baz[1]'s area:" << baz[1].area() << '\n';       
  delete bar;
  delete[] baz;
  return 0;
}   

I am a bit (no pun intended) confused about this line of code here:

baz = new Rectangle[2] {{2,5}, {3,6}};

I've seen code like:

int *foo = new int[3] {1,2,3};

and I totally understand it. But what's the syntax of {{2,5}, {3,6}} here? How can array of class objects be initialized like this? I've searched many online c++ references but have no clue.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire