Thread: Is there a way for a program to generate the name of an instance of a class?

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    16

    Is there a way for a program to generate the name of an instance of a class?

    Wordy title.. Lemme try to explain better.

    I'm trying to design a database-like program to see how well I can use file input/output, menus, and other stuff I've been working on in one single program. I want to use a class/structure to represent the format for one entry in the database, and then have instances of that class for specific entries. However, I don't know how to make the program generate the name for the instance.

    If you don't understand, what I mean is whenever you declare an instance of a class, like this for example:

    Code:
    class randomClass
    {
    [insert class definitions here]
    }
    
    randomClass entry_1
    entry_1.definition1 = 5
    and so on. My problem is that the program only knows how to create "entry_1", and thus only knows how to create as many as I tell it. Is there a way around this?

    Thanks.

  2. #2
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    I'm not sure I understand, but perhals you are asking how to create a collection of randomClass
    objects.

    Here's an example:
    Code:
    #include<vector>
    
    RandomClass {
      RandomClass(int){};
    }
    
    int main(){
      std::vector<RandomClass> instances; //create a vector of RandomClass
      for(int i=0;i<10;++i) // for each number 0 to 9
        instances.push_back(RandomClass(i)); //create a RandomClass object and put it in the vector
      instances[7];//get the 7th RandomClass
    }
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  3. #3
    Registered User
    Join Date
    Dec 2009
    Posts
    16
    That might be what I need.. would it be possible for that same method to be put into a function so a class can be created at the user's request?

    Edit: Lemme make sure I follow this, cause I don't. What is a vector, what does push_back() do?

  4. #4
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    A vector is a class that acts like an array; it lets you add more objects to the end of the array using the push_back() function.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  5. #5
    Registered User
    Join Date
    Dec 2009
    Posts
    16
    So if I'm understanding this right...

    Code:
    #include <vector>
    
    int dbSize = 0;
    
    struct db_entry; //creates structure
    {
        int value1;
        int value2;
        int value3;
    }
    
    std::vector<db_entry> data; //creates vector for db_entry
    
    void addNewEntry()
    {
        dbSize++
        data.push_back(db_entry(dbSize)); //adds one to the vector of db_entry then asks the user for their value
        cin>>data[dbSize].value1;
        cin>>data[dbSize].value2;
        cin>>data[dbSize].value3;
    }
    
    cout<<data[1].value2; //accesses the first db_entry
    The function addNewEntry can, at any point, add one to the vector, give it it's values, and then call it later as data[1]? Anything I'm missing?

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    More like:
    Code:
    void addNewEntry(std::vector<db_entry>& data)
    {
        data.push_back(db_entry());
        cin >> data.back().value1 >> data.back().value2 >> data.back().value3;
    }
    Basically, you want to default construct a db_entry object and put it into the vector. Then you read into the members of this db_entry object at the back of the vector.

    I used a reference parameter. You do not need a global variable here. You do not need the dbSize variable since you can obtain the size from the vector.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Dec 2009
    Posts
    16
    Hooray, more code I don't completely understand xD

    1. what does back() do? how is it different from push_back()?

    2. With your function, what would I use to output? would it still be data[1].value2?

    3. what's with putting the vector.. is it a declaration? whatever it is, why is it in the part of addNewEntry() where the arguments would go?

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by verxintRising
    1. what does back() do? how is it different from push_back()?
    It returns a reference to what push_back() just pushed at the back

    Quote Originally Posted by verxintRising
    2. With your function, what would I use to output? would it still be data[1].value2?
    Yes, but of course you can give the vector a different name in the caller function if you wish.

    Quote Originally Posted by verxintRising
    3. what's with putting the vector.. is it a declaration? whatever it is, why is it in the part of addNewEntry() where the arguments would go?
    It is a (formal) parameter. Indeed, you would pass the vector as an argument.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Dec 2009
    Posts
    16
    Alright, im getting this now.. I'm a bit neurotic about using code I don't understand well so bear with me..

    back() references whatever is the last value in a vector (or array?). So in this case, it automatically selects whatever was last added to the vector. Got that. So then, what do I use to see how long the vector is. is it something like data.length()?

    When I call addNewEntry() in the program, do I actually have to put any arguments in the parenthesis? I'm still a bit lost as to why the vector has to be declared in the argument for the function. Also, why is there a & before data?

    It seems like putting the vector in the arguments of the function would mean I can't call it anywhere else in the program.. :S

  10. #10
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Quote Originally Posted by verxintRising View Post
    Alright, im getting this now.. I'm a bit neurotic about using code I don't understand well so bear with me..

    back() references whatever is the last value in a vector (or array?). So in this case, it automatically selects whatever was last added to the vector. Got that. So then, what do I use to see how long the vector is. is it something like data.length()?

    When I call addNewEntry() in the program, do I actually have to put any arguments in the parenthesis? I'm still a bit lost as to why the vector has to be declared in the argument for the function. Also, why is there a & before data?

    It seems like putting the vector in the arguments of the function would mean I can't call it anywhere else in the program.. :S
    If you declare a variable in a function, be it a vector or something else, it is not accessible anywhere else outside that function by default.
    This can, of course, be solved by using global variables, but those are considered bad practice and should be avoided at all costs. There is no need for them. Everything can be solved without them.

    In your scenario, you would most likely want to declare your vector in main. Then, at some point, you would want to add an entry to the vector, and you might want to do it the way you wanted to; e.g. call a function that gets the data from the user and adds it to the vector.
    This is why you would pass the vector to the function in question. However, if your function accepts the vector like so:

    Code:
    void foo(std::vector<someType> vec) { .. }
    It will make a copy of the vector. This means you would be adding values to a copy of your main vector, and when the function finished running, the vector in main would remain untouched.

    To solve this, you pass by reference by either making your function take a pointer to a vector, or a reference. References are more or less the same as pointers, except they are immutable, and they provide cleaner syntax. Pointers and references are both good, but for different things.

    I'm not sure how far you are into learning C++, but you might not understand references yet. If so, I suggest you read up on them, as they shouldn't be too hard to grasp.
    "What's up, Doc?"
    "'Up' is a relative concept. It has no intrinsic value."

  11. #11
    Registered User
    Join Date
    Dec 2009
    Posts
    16
    I don't know anything about references, but I do understand pointers.

    I'm wondering though, why are global variables bad? I've used them a few times and I don't see what can go wrong. And since they are wrong, exactly how do you get around them? wouldn't using a pointer still basically be declaring a global variable?

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by verxintRising
    So then, what do I use to see how long the vector is. is it something like data.length()?
    Almost: data.size()

    Quote Originally Posted by verxintRising
    I'm wondering though, why are global variables bad? I've used them a few times and I don't see what can go wrong.
    I have two reasons here.

    Quote Originally Posted by verxintRising
    And since they are wrong, exactly how do you get around them?
    Provide your functions with parameters and pass arguments appropriately. Make use of function return values.

    Quote Originally Posted by verxintRising
    wouldn't using a pointer still basically be declaring a global variable?
    No, it would not. The aliasing involved is akin to how a global variable can be changed by any function call, but at least there is some indication that the variable could be changed, and if the pointer/reference is a pointer/reference to const, it cannot (at least not without subverting const-ness).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    Quote Originally Posted by verxintRising View Post
    I don't know anything about references, but I do understand pointers.

    I'm wondering though, why are global variables bad? I've used them a few times and I don't see what can go wrong. And since they are wrong, exactly how do you get around them? wouldn't using a pointer still basically be declaring a global variable?
    I'm not sure why you think a pointer is a global variable. Passing something declared only in a single function to some other function by ref/pointer means that it can only be modified in those two functions.

    Anyway, to get around using them, you just have to pass your stuff to your functions.

    The reason behind the perpetuated "no global variables" mantra is because using them can only result in bad things. The little good they do bring is outweighed by the bad.

    Imagine a massive project, with several different programmers, and a global variable. A programmer might modify the variable because he thought it was what he needed to do at the time - and maybe it was - but forgets to restore it to the state it was in.
    There is no telling what might happen if he were to do it. Who's to say the function that called his function wasn't using it in the state it was in?

    There are limitless scenarios where they can only be bad, but they probably all preach that it's hard to know where, if or when they're being modified if you have a huge project.

    Of course, if you don't have a huge project and you're the only programmer working on it, those risk might be miniscule, but in the end you'll just be stuck with bad programming habits, so you should try to avoid them.
    "What's up, Doc?"
    "'Up' is a relative concept. It has no intrinsic value."

  14. #14
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Your C++ book should tell you about things like vector, but I'd recommend bookmarking this site: C++ Reference [C++ Reference]
    There you can read about all the member functions of vectors as well as other STL functions & classes like lists & maps...
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  15. #15
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    While not so much anymore but 20 years ago the two biggest sources of pain when trying to debug OPC (Other Peoples Code) were globals and macros that hid huge blocks of code. The former was bad for all of the usual reasons (module L modified the global behind the back of module A) and the latter drove you insane trying to debug it when you hit something that looked like DO_FUNC(A); only the find that it hid 40 lines of C code....grrrr
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need the code of few programs in c++.plzzzzz help...plzzz
    By NAVINKR20 in forum C++ Programming
    Replies: 1
    Last Post: 05-08-2009, 09:13 AM
  2. instance of a class disappearing after function ends
    By combatdave in forum C++ Programming
    Replies: 14
    Last Post: 10-20-2006, 08:59 AM
  3. Replies: 8
    Last Post: 10-02-2005, 12:27 AM
  4. Declaring an instance of a class inside a class
    By nickodonnell in forum C++ Programming
    Replies: 4
    Last Post: 10-01-2005, 11:46 PM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM