Home > Software design >  Pass data from object in class A to class B
Pass data from object in class A to class B

Time:09-22

New to classes and objects in c and trying to learn a few basics

I have the class TStudent in which the Name, Surname and Age of student are stored, also I have the constructor which is accessed in main and inserts in the data. What I want to do is: having the class TRegistru, I have to add my objects data in it, in a way that I can store it there, then I could save the data in data.bin and free the memory from the data, then I want to put the data back in the class and print it out.

The question is: In what way & what is the best way to add my objects in the second class, so that I could eventually work with them in the way I've described in the comments, so that I won't have to change nothing in main

Here's my code so far:

#include <iostream>    

using namespace std;

class TStudent
{
public:
    string Name, Surname;
    int Age;

    TStudent(string name, string surname, int age)
    {
        Name = name;
        Surname = surname;
        Age = age;
        cout <<"\n";
    }
};

class TRegistru : public TStudent 
{
public:
    Tregistru()        
};

int main()
{
    TStudent student1("Simion", "Neculae", 21);
    TStudent student2("Elena", "Oprea", 21);
    TRegistru registru(student1);//initialising the object
    registru.add(student2);//adding another one to `registru`
    registru.saving("data.bin")//saving the data in a file
    registru.deletion();//freeing the TRegistru memory
    registru.insertion("data.bin");//inserting the data back it
    registru.introduction();//printing it

    return 0;
}

CodePudding user response:

Hence the question is about passing data from A to B, I will not comment on the file handling portion.

This can be done in multiple ways, but here is one of the simplest and most generic. By calling TRegistru::toString() you serialize every TStudent added to TRegistru into a single string which then can be easily written to a file.

Demo

class TStudent
{
public:
    std::string Name, Surname;
    int Age;

    std::string toString() const
    {
        return Name   ";"   Surname   ";"   to_string(Age);
    }
};


class TRegistru
{
public:
    void add(const TStudent& student) 
    {
        students.push_back(student);
    }

    void deletion() 
    {
        students.clear();
    }

    std::string toString() const
    {
        std::string ret{};
        for(const auto& student : students)
        {
            ret  = student.toString()   "\n";
        }
        return ret;
    }

    std::vector<TStudent> students;
};
  • Related