I’m a beginner to C++ programming, and I’m wondering how you would go about passing a struct as an argument to a function using cin.
The idea of the code is to input the name of a struct from the user, and have that name be passed to a function. Here’s what I’ve been playing around with:
class myPrintSpool
{
public:
myPrintSpool();
void addToPrintSpool(struct file1);
private:
int printSpoolSize();
myPrintSpool *printSpoolHead;
};
struct file1
{
string fileName;
int filePriority;
file1* next;
};
int main()
{
myPrintSpool myPrintSpool;
myPrintSpool.addToPrintSpool(file1);
return 0;
}
This is able to build. However, I wanted something more along the lines of:
class myPrintSpool
{
public:
myPrintSpool();
void addToPrintSpool(struct fileName);
private:
int printSpoolSize();
myPrintSpool *printSpoolHead;
};
struct file1
{
string fileName;
int filePriority;
file1* next;
};
int main()
{
string fileName;
cout << "What is the name of the file you would like to add to the linked list?";
cin >> fileName;
myPrintSpool myPrintSpool;
myPrintSpool.addToPrintSpool(fileName);
return 0;
}
Can anyone help how I would go about doing this? Thanks in advance!
This sort of metaprogramming is, in general, extremely advanced in C++. The reason is, unlike interpreted languages, much of what exists in the source file is lost when the file is compiled. In the executable, the string
file1may not show up at all! (it’s implementation dependent, I believe).Instead, I would recommend doing some sort of lookup. For instance, you can compare the string passed in in fileName to each struct’s
fileName, or, you can just associate any key with your struct. For instance, if you created astd::map<string, baseStruct*>and inherited all of your structs (e.g. file1, file2, …) frombaseStruct, then you can lookup in the map which struct is associated with the passed in string. The inheritance is important, because you will need polymorphism to insert structs of differing types into the map.There are many other, more advanced topics that we could get into, but this is the general idea. It’s most simple to do some sort of lookup rather than try to instantiate a type at runtime from a string. Here is a more rigorous and more maintainable approach to doing basically the same thing.
EDIT: If you mean you have only one type of struct called ‘file1’ and you want to instantiate it and pass it to addToPrintSpool, that’s different than my previous answer (which applies if, for example, you want to have multiple structs called file1 and file2 and want to infer which struct to use. Figuring out types dynamically from a string is hard, but setting the string in an instance of a known type is straightforward.)
To instantiate and use an instance of
file1you can do this: