tags:

views:

69

answers:

2

I recently debugged a strange C++ problem, in which a newly declared vector somehow had a size of 477218589. Here's the context:

struct Triangle {
    Point3 a,b,c;
    Triangle(Point3 x, Point3 y, Point3 z) : a(x), b(y), c(z) {}
    Vector3 flat_normal() { return (a-c)^(b-c); }
};

vector<Triangle> triangles;

Calling triangles.size() returns the value 477218589. I 'fixed' the problem by changing struct Triangle to class Triangle, but I'm wondering why there's any difference. Should I have done that typedef struct Foo { ... } Foo; magic? If so, why would that help?

If it matters, I'm using g++-4.1.

+1  A: 

There shouldn't be any difference between declaring Triangle as a struct or class - in C++, the difference between the two is that the default access specification of the members is public for struct and private for class, but that's it.

Is there anything more to Triangle that you didn't include?

Timo Geusch
I didn't think there was a difference, either! I've added the full contents of `Triangle`. `Point3` and `Vector3` are simple classes.
perimosocordiae
+1  A: 

This

#include <vector>
#include <iostream>

struct Point3 {};

struct Triangle {
    Point3 a,b,c;
    Triangle(Point3 x, Point3 y, Point3 z) : a(x), b(y), c(z) {}
};

int main()
{
    std::vector<Triangle> triangles;

    std::cout << triangles.size() << '\n';

    return 0;
}

prints 0 for me. If it also does for you, then the problem is in parts of the code not included in this snippet. If it prints anything else, something is fishy with your compiler/std lib/setup.

sbi
Well, here's an afterthought: You cannot use a type with a `std::vector`, unless it provides a default constructor. (My compiler doesn't detect this since the code snippet never attempts to populate the vector.) Since `Triangle` doesn't provide a default constructor, technically it might be invoking undefined behavior.
sbi
@sbi: Default constructor is only required if you call methods and want to use the defaults. `vec.resize(10);` - default constructor required or it won't compile otherwise, `vec.resize(10, Something(x, y));` - default constructor not required.
UncleBens
@UncleBens: Thanks for the clarification!
sbi