0

I am trying to learn the best practices while improving my C++ skills and I've got a question.

If I have, for example this, struct:

struct Vector {
    int x;
    int y;
};

typedef struct {
    Vector position;
    Vector velocity;
} Ball;

Which one would be the correct way to initialise it?

Ball* _ball1 = new Ball();
Ball* _ball2 = new Ball;

I know it would be better to create a class in this case, but I am trying to use all kinds of structures etc.

Also, regarding the struct definition - instead of typedef struct {} Ball;, would it be better just: struct Ball{}; ?

Any insight would be much appreciated.

Thanks!

Edit: Thank you everyone for the answers!

Eideann
  • 67
  • 4
  • 3
    `typedef struct` is something you do in `c` but not needed in `c++` – drescherjm Mar 22 '22 at 13:36
  • 2
    Why is a pointer and `new` required at all? This should always be the last choice. Just declaring the object directly or if that isn't possible using `std::unique_ptr` should be the default. – user17732522 Mar 22 '22 at 13:37
  • 2
    You don't need pointers here. Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Mar 22 '22 at 13:38
  • 1
    In `c++` a `struct` and a `class` are basically the same thing with a `struct` having members public by default and a `class` they are private. Related: [https://stackoverflow.com/questions/54585/when-should-you-use-a-class-vs-a-struct-in-c](https://stackoverflow.com/questions/54585/when-should-you-use-a-class-vs-a-struct-in-c) – drescherjm Mar 22 '22 at 13:38
  • 4
    `Ball _ball1 = new Ball();`. No. Just simply `Ball _b;` or `Ball _b{};` – PaulMcKenzie Mar 22 '22 at 13:41
  • *// Vector is another struct with two integers: x and y* -- So why didn't you put it in the post? I'm sure the edit window is large enough so that you could have simply added this `struct` to the question. Probably would have taken less keystrokes than putting a comment there. – PaulMcKenzie Mar 22 '22 at 13:43
  • 4
    This is a common mistake made by developers coming to c++ from object oriented languages like Java and C#. You don't need `new` to create an instance. If your object has automatic storage duration (its lifetime is bound to a scope) then just `Ball _ball1;` will work to create a default constructed instance. `new` can be used to create instance with dynamic storage duration but even then in modern c++ it is generally not used and `std::make_unique()` would be preferred. See [`std::unique_ptr`](https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one). – François Andrieux Mar 22 '22 at 13:56
  • `new Ball()` and `new Ball` are equivalent (though as others have noticed neither is best practice) – Alan Birtles Mar 22 '22 at 13:58
  • 2
    [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) – 463035818_is_not_an_ai Mar 22 '22 at 14:00
  • 2
    this is a so common misconception that Bjarne has it in many of his presentations. To create an object in C++ you do `Ball b;`. No pointer and no `new` needed. In case you are coming from Java, you need to forget everything you know about it to learn C++ – 463035818_is_not_an_ai Mar 22 '22 at 14:01
  • Thank you everyone! I am following Bjarne's book, still learning so, this is why I am here, hehe. In there, at least in the revision I have, he uses pointers to struct in order to pass it as parameters for some functions, that's why I was trying to play with it this way. I think I will need to first properly learn about memory allocation, as I noticed I don't have idea yet. Thank you for your answers! Really helpful. – Eideann Mar 22 '22 at 17:15
  • So, to check if I understood it correctly. I should NOT use an struct as a pointer, never? Not even if I need to pass it as parameter to a function? – Eideann Mar 22 '22 at 17:26
  • 1
    "I should NOT use an struct as a pointer, never?" its not never, but almost. You can go a long way before you need your first pointer. To pass function parameters prefer references – 463035818_is_not_an_ai Mar 22 '22 at 18:41

1 Answers1

1

First, you can do this:

Ball ball;

You now have a local Ball object. It will last until the enclosing code is closed. That is:

cout << "Foo\n";
if (true) {
    Ball ball;
}
cout << "Bar\n";

The ball exists only inside those {}. If you try to use it outside (where the cout of Bar is found), it won't be there. So in many cases, your variables will be alive for the scope of a function call.

void foo() {
   Ball ball;
   ...
}

This is the easiest thing to do, and it probably works for most of your use cases. You probably don't need to worry about pointers for your first pieces of code.

However, if there's a reason you want to really use pointers, you can do this:

void foo() {
    Ball * ball = new Ball;
    ... make use of it
    delete ball;
}

If you don't do the delete, you have a memory leak. Unlike Java, C++ doesn't have any sort of garbage collector. You're on your own.

But you can also do this:

void foo() {
    std::shared_ptr<Ball> ball = std::make_shared<Ball>();
    ... use it
    ... no delete required
}

These are referred to as smart pointers, and the trend in C++ is to use either unique_ptr or shared_ptr instead of raw pointers. (Raw pointers are what I did in the previous example.) These work more like C++ objects, where when you lose all the pointers, it knows and deletes the memory for you. This is referred to as RAII (Resource Acquisition Is Initialization), and you're strongly, strongly encouraged to learn it.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36
  • Thank you so much! Really appreciated. I didn't know about `shared_ptr` or `unique_ptr`. I see some open source projects using pointers for instanced objects, something like `ObjectClass* obj = new ObjectClass()`. Do you mean this should not be done and the `shared_ptr` should be used instead? Thanks once again! – Eideann Mar 22 '22 at 17:11
  • 1
    A lot of old-school programmers still use raw pointers, but switching to smart pointers will eliminate a bunch of bugs. – Joseph Larson Mar 23 '22 at 18:20
  • Thank you! Yes, I noticed. I just started programming again in C++ after around 12 years, and well, there are many new and interesting things, hehe. Time to study about all this. – Eideann Mar 23 '22 at 19:15