google11video
google11video

Reputation: 63

Error when initializing heap-allocated object

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

Upvotes: 1

Views: 176

Answers (5)

Pubby
Pubby

Reputation: 53047

This works in C++11:

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

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

Upvotes: 0

Azodious
Azodious

Reputation: 13872

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);

Upvotes: 0

masoud
masoud

Reputation: 56479

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
}

Upvotes: 0

Mysticial
Mysticial

Reputation: 471299

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.
}

Upvotes: 3

Zach Rattner
Zach Rattner

Reputation: 21353

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.

Upvotes: 0

Related Questions