Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible/advised to store a vector in a struct? C++

Tags:

c++

struct

vector

I always have thought of a struct as a fixed sized object and while there doesn't seem to be any glaring compiler errors, I was wondering if doing this is generally in good practice. Would changing the struct to a class be more advisable or will a struct do just as well?

The code, just because people get fussy:

struct Sprite
{
    float x;
    float y;
    std::vector<Sprite> sprite;
}

The essence of what I am doing is having children of a class as the same type as the parent. When the parent dies, the children do too.

like image 253
Satchmo Brown Avatar asked Jun 12 '12 22:06

Satchmo Brown


2 Answers

An std::vector has a specific known size, and any class or struct that contains it has a specific known size. std::vector allocates memory on the heap to act as a variable sized array and stores a pointer to said memory. The only difference between a struct and a class is that a struct is defaultly public, and a class is defaultly private.

like image 133
David Avatar answered Nov 15 '22 15:11

David


The differences between struct and class have to do with member visibility: the most notable difference is that struct's members are public by default, and also that struct's inheritance is public by default; class members and class inheritance are both private by default. Other than that, there is no difference: you can always write code with struct that produces code equivalent to code written with class, and vice versa.

like image 45
Sergey Kalinichenko Avatar answered Nov 15 '22 16:11

Sergey Kalinichenko