• Advertisement
Sign in to follow this  

constructor problem

This topic is 4326 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a struct like this: struct CVector3 { public: float x, y, z; }; And I have a lot of places in the program were I initialize like this: CVector3 vector = {0,0,0}; But when I make a constructor like this: struct CVector3 { public: float x, y, z; CVector3(float a, float b, float c){x=a; y=b; z=c;} }; It says that I cant initialize the same way that I did before and I have to use the constructor. Is any way to use both of the ways? Thanks.

Share this post


Link to post
Share on other sites
Advertisement
0) You should be implementing the constructor this way instead:

CVector3(float a, float b, float c) : x(a), y(b), z(c) {}

1) Using the constructor is as simple as 'CVector3 vector(0, 0, 0)', so why do you care?

Share this post


Link to post
Share on other sites
I spent a bit fussing over this as well, but it's just one of those language quirks. Kind of like templated typedefs :)

Share this post


Link to post
Share on other sites
"Constructor" is for C++

class CVector
{
public:
x, y, z;
CVector(float a, float b, float c)
{
//blah
}
};


So the answer is no, unless by some crazy thing I dont know about C. And p.s, in a Struct everything is public, so you dont need to declare it public. Basically my guess is that if your compiler accepts the keyword "public" I would assume its mixing c/c++ code, and thats why it said the word 'constructor'.

Share this post


Link to post
Share on other sites
There is no difference between a struct and a class in c++ except that a struct is public by default (to stop old code breaking) and a class is private by default. You can still have explicitly public and private sections in structs (and even protected AFAIK).

Share this post


Link to post
Share on other sites
struct and class are the same in C++ apart from the default access being private in a class.

You can init your types like this too, same as you can do with build in types except that there are no user defined literals.

v = vector3D(0,0,0);

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement