eslam saad
eslam saad

Reputation: 73

Class C++ trace this value!

#include <iostream>
using namespace std;

class t
 {     public:
  int health; //its members
  int speed;
  int power;
  void attack() // its methods
{ cout<<"I'm attacking"<<endl;
  };
  };

int main()
{   t A,B,C,D;
A.power = 100;
B.health = 87;
C.speed = 92;
cout<<"A= "<<A.power<<"B= "<<A.health<<"C= "<<A.speed<<endl; // <---
cout<< "My health is "<<C.health<<" My speed is "<<A.speed<<endl;
cout<<"My power is "<<B.power<<endl;
D.attack();

system("pause");
return 0;}

The output result was :: A= 100 B= 96 C=6234392 <--- From where these values come

Upvotes: 1

Views: 351

Answers (3)

Andrew Rasmussen
Andrew Rasmussen

Reputation: 15099

You should create a constructor to initialize those values to some default value in the initializer list.

class t {
public:
t() : health(100),power(100),speed(100) {}
// ...
};

This will guarantee that those values are all set to 100, or some default, or even an input parameter, rather than garbage. It's considered much better design since otherwise the initialization of those values would be handled in the constructor that the compiler generates for you behind the scenes.

Upvotes: 2

Drahakar
Drahakar

Reputation: 6088

Uninitialized memory?

Uninitialized variable won't be zero setted at the creation of the class/struct. You need to manualy do it. Otherwise, you will get whatever_is_in_memory_at_that_time.

Upvotes: 0

icktoofay
icktoofay

Reputation: 129109

A.health and A.speed are just junk values on the stack because you didn't explicitly set them. If you want to initialize all fields of A to zero, you can use memset:

memset(&A, 0, sizeof(A));

Upvotes: 3

Related Questions