1

I am trying to initialize a heap-allocated object as follows:

class Ball {
  int radius;
  string colour;
};

int main(){
    Ball *b = new Ball { radius = 5, colour = "red" };
}

Wondering why this is giving me an error? Thanks

  • Please pick up a [Good Book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Alok Save Nov 12 '11 at 07:14
  • If you have a c++0x compiler, have a look here at initializer lists http://en.wikipedia.org/wiki/C%2B%2B11. If you have a c++98 compiler... Anyway in both ways your code is wrong. – joy Nov 12 '11 at 08:24

5 Answers5

3

That's not how you initialize an object in C++.

Here's one way to do it:

class Ball {
    int radius;
    string colour;

public:

    //  Define a Constructor
    Ball(int _radius, const string &_colour)
        : radius(_radius)
        , colour(_colour)
    {
    }
};

int main(){
    Ball *b = new Ball(5, "red");

    delete b;  //  Don't forget to free it.
}
Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • Why the `_`s? No ambiguity without them. – Pubby Nov 12 '11 at 07:14
  • Probably more like "reader" ambiguity. But you're right, it does actually work without the `_`. I was under the impression that the parameters will shadow the fields, but I guess it doesn't apply to initializer lists. – Mysticial Nov 12 '11 at 07:19
0

Use () instead of {}. You're calling a constructor, which is just a special function that instantiates an object.

So, the syntax looks like this:

Ball* b = new Ball(5, "red");

Also note that the parameter order in the constructor (5 before "red") dictates which variable get assigned to which value. So, you don't put the variable name in the constructor call.

Zach Rattner
  • 20,745
  • 9
  • 59
  • 82
0

Many issues!

Try this:

class Ball {
public:
  Ball(int r, const string &s)
  {
    radius = r;
    colour = s;
  }
  int radius;
  string colour;
};

int main(){
    Ball *b = new Ball(5, "red");
    // ....
    // delete b;  <-- dont forget
}
masoud
  • 55,379
  • 16
  • 141
  • 208
0

When creating an object use ( ... ) in place of { ... } and no need to write variable name. just pass the value to be assigned.

Ball *b = new Ball { radius = 5, colour = "red" };` // Wrong

change it to

Ball *b = new Ball ( 5, "red" );

and, don't forget to declare a constructor in your Ball class, in public section.

Ball(int, std::string);
Azodious
  • 13,752
  • 1
  • 36
  • 71
0

This works in C++11:

struct Ball {
  int radius;
  std::string colour;
};

int main() {
  Ball* b = new Ball({ 5, "red" });
}
Pubby
  • 51,882
  • 13
  • 139
  • 180