-1

so I have a class Data which has a multiset container and I have a class Item which has "erscheidatum" as one of the constructor parameters,so I want this parameter escheidatum to be inserted in the multiset in the data class i tried to do that in the constructor of the Item class but when I am printing the set its empty the console is empty,i dont know if its possible to insert a set from another class.

//this is Item.h file 
#include"Data.h"
#include<string>
class Item
{
public:
    Item(std::string Name,int erschDatum, Data pd)// i put Data variable here though that i dont need it  just to get access to->
    :_Name(Name), dataobject(pd), _erda(erschDatum)//->data class maybe its not the best way.
     {
       dataobject.insert(erschDatum);
     }

    ~Item();
    
private:
    Data dataobject;
    std::string _Name;
    int _erda;
    };

and this is my Data.h file

#include<set>
#include<iostream>

class Data
{
public:
    Data();
    std::multiset<int>dataset;
    void insert(int a) {
        dataset.insert(a);
    }
    void showData() {
        for (const auto& e : dataset) {
            std::cout << e << std::endl;
        }
    }
    
    ~Data();

};

and this the main function

#include<iostream>
#include"Item.h"
#include"Data.h"


int main(){
Data DaOb;  
Item Buch("xy", 1996,DaOb);
DaOb.showData();
}


JaMiT
  • 14,422
  • 4
  • 15
  • 31
Dr.Noob
  • 319
  • 6
  • 17

1 Answers1

2

You should use reference of Data as parameter of Item. Like this

class Item
{
public:
    Item(std::string Name,int erschDatum, Data& pd)// i put Data variable here though that i dont need it  just to get access to->
    :dataobject(pd), _Name(Name),  _erda(erschDatum)//->data class maybe its not the best way.
     {
       dataobject.insert(erschDatum);
     }

    ~Item();

private:
    Data& dataobject;
    std::string _Name;
    int _erda;
};
Anton Shwarts
  • 515
  • 2
  • 10
  • 1
    Changing a member to a reference usually requires a bit more thought, so that you don't run into dangling references. – JaMiT Jun 19 '20 at 23:42
  • You are right. It just example. If you want to escape dangling references you can use smart pointers, I think. I wrote this answer from smartphone, sorry – Anton Shwarts Jun 19 '20 at 23:46