Skip to main content
GameDev.net gamedev.net
🔒 Locked

constructor problem

Started by daniel_i_l Apr 21, 2006 at 2:27 AM 5 replies 500+ views
Original Post
daniel_i_l
daniel_i_l
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.
"We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare. Now, thanks to the internet, we know this is not true." -- Professor Robert Silensky
Zahlman
Zahlman
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?
hh10k
hh10k
I spent a bit fussing over this as well, but it's just one of those language quirks. Kind of like templated typedefs :)
dpadam450
dpadam450
"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'.
NBA2K, Madden, Maneater, Killing Floor, Sims 
Aardvajk
Aardvajk
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).
simon10k
simon10k
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);
-----------------------------Language: C++API: Win32, DirectXCompiler: VC++ 2003
simon10k
simon10k
heh, you beat me to it =)
-----------------------------Language: C++API: Win32, DirectXCompiler: VC++ 2003

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.