constructor

Hi guys,

I am wondering about c++ default constructor.

Let's say I am trying to define a class, and letting default constructor to initialise it's value. The result of initialized variable is (using type int) -858993460> Why is it so?

Last edited on
The clairvoyants are off duty now.
Can you show the code so that ordinary programmers can have a look?
I beg your pardon

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

class darbuotojas
{
public:

	
	int get_amzius()
	{
		return amzius;
	}
	void set_amzius(int amzius);

	void give_amzius()
	{
		cout << "darbuotojo amzius - " << get_amzius() << endl;
	}

private:
	int amzius;
};

#include "darbuotojas.hpp"
using namespace std;



void darbuotojas::set_amzius(int naujas_amzius)
{
	amzius = naujas_amzius;
}

int main()
{
	darbuotojas ateina;
	ateina.give_amzius();
	ateina.set_amzius(20);
	ateina.give_amzius();
	ateina.set_amzius(25);
	ateina.give_amzius();

	return 0;
}

At the moment nobody initializes the var amzius. The compiler will create a default constructor for you but it doesn't know anything about your vars.
The best is to create a constructor yourself like:

1
2
3
4
5
6
7
8
9
10

class darbuotojas
{
public:
  darbuotojas(int a) { amzius = a;}
  // and/or
  darbuotojas() { amzius = 0; // or any other value}

  // allyour code here
};


BTW. What does darbuotojas mean? What language is it?
Employee. It is Lithuanian
Why is it so?

Because POD (plain old data) types are not initialized to any particular value unless you let the compiler know you want them to be.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

struct Pod
{
    int value;
};


void avoid_uninitialized_error(Pod&) // To fake out VC++.
{
}

int main()
{
    {
        Pod p;  // uninitialized

        avoid_uninitialized_error(p);

        std::cout << p.value << '\n';
    }
   
    {
        Pod p = Pod();  // initialized

        std::cout << p.value << '\n';
    }

}


Thanks!
Topic archived. No new replies allowed.