Search code examples
c++stringdynamicclass-members

Class containing strings - Can I skip initialising them and if so how?


happy coders!

I had a plan to try to learn some C++ today and so I thought I could take an old C assignment from a previous course and just do the same thing in C++. The assignment is to read music files and retrieve data from their ID3 tags and sort them in folders according to their artist, album and track title etc etc... this does not really matter but you know at least what I'm going for.

So I played around a little with sets and made my program receive an array of strings specifying different songs which it will loop the algorithm over.

In this next step I got stuck though due to how I tried to copy the behaviour of my old C program which was a struct containing three values being:

int size;
char *tag_name;
char *data;

but so far I have been unable to recreate this dynamic behaviour in C++ where I wish to only have the members defined but not initialised since I wanted to be able to change this data later on. Technically I can do this in a way where I get the data from the file before I create the tag, and therefore give the constructor their initial values and be done with it. But can I do it in the way I want to?

class Tag {
 public:
   std::string name;
   std::string data;
   int size;

   Tag() {}
   Tag(std::string n, std::string d, int s) : name(n), data(d), size(s) { }
   void setData(std::string data) { this.data = data }
};

Since I've tried a billion combinations of pointers and whatnot (Googled loads) I just returned to the above and decided to ask you how to actually accomplish this.

My brained is completely mashed but consider the above psuedo code since I bet it is not correct in any way...

So my question is: How do I define a class so that I get a dynamic string allocation for the members name and data? I was almost thinking of using some good old char* but the point of me trying this was to learn some C++, so I am forcing myself to go through this now.


Solution

  • If I understand your question correctly, your default constructor already takes care of this. Your std::strings will initialize to empty string "". You can assign a different value to this string at any time.

    If you really wanted to, you could change your default constructor to

    Tag() : name(""), data(""), size(0) {}