get private variable from public function

Hello everyone,
I am new in the C++ world of programming and I am getting desperate with the following code. Basically, I am trying to get a variable defined as private in my class from a public function. The variable is actually a set of integers. My code is divided into three different files:

data.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstdio>
#include <set>

using namespace std;

class Data{

 public:
  Data();
  ~Data();

  void add_datum  (int );
  set<int>  get_data(void );
  
 private:
  set<int> data;
};


data.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "data.h"

Data::Data(){

  data.clear();
}

Data::~Data(){

  data.clear();
}

set<int> Data::get_data(void ){
  return data;
}

void Data::add_datum(int i){
  data.insert(i);
}


and main.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <iostream>
#include <cstdio>
#include "data.h"

using namespace std;

int main (int argc, char **argv){

  Data d;

  for (int i=0; i<10; i++)
    d.add_datum(i);

  printf("size %d ",(int)d.get_data().size());
  for(set<int>::iterator it=d.get_data().begin(); it!=d.get_data().end(); it++)
    printf("%d ",*it);
  printf("\n");

  return 0;
}


The object set is supposed to contain integers from 0 to 9, but when I try to iterate through its elements by making use of the function "get_data()" I can not get the whole set, but only some of the elements, even though it seems to be correct, since d.get_data().size() is 10. The execution gives me:

./main
size 10 3 9

Any ideas? I guess I must be doing something really wrong, but I cannot figure out what... Many thanks in advance.
each time you call get_data(void ) you get a copy of data, hence d.get_data().begin() and d.get_data().end() are from different object. It's not defined what happens.

Better return a reference, like so:

const set<int> &get_data(void );
Hi coder777

thank you for your answer and your explanation, now I understand. Your suggestion solved the problem :)
Topic archived. No new replies allowed.