Reputation: 317
I'm really new to c++. I have a simple console application with an header.h
that holds my class
class MyClass
{
public:
float x, y, z;
MyClass(float x, float y, float z);
};
I have a implement.cpp
with all my implemented methods and I have
MyClass::MyClass(float x, float y, float z) {};
Then in main.cpp
I try to simply print the values
int main()
{
MyClass One(-3.0f, 0.0f, 4.0f);
cout << "Firsth Object: " << One.x << ", " << One.y << ", " << One.z << endl;
}
But in console values are printed like :
-1.07374e+08, -1.07374e+08, -1.07374e+08
What am I doing wrong?
Upvotes: 0
Views: 383
Reputation: 21514
Your constructor did not initialize any of the members: MyClass::x
, MyClass::y
nor MyClass::z
.
You must do:
MyClass::MyClass(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
};
or better yet (more idiomatic, and possibly faster):
MyClass::MyClass(float x, float y, float z) :
x( x ), y( y ), z( z )
{
};
Without that, you're printing the values of uninitialized members of the MyClass
object One
. In general, you must always initialize members of a class before you can use them.
Upvotes: 5
Reputation: 12648
Your current constructor does nothing.
You have to initialize your objects variable. For this you can use
MyClass::MyClass(float x, float y, float z) : x(x), y(y), z(z)
{
}
This type of initialization in constructors is called initializer list, you can read it up here.
This has the same effect as the constructor pointed out by @jpo38.
Upvotes: 2