Using the same variable (and its value) in different classes



  • Hi,
    I have variable QString name in a class named Additem. I want to manipulate it in class Review and transfer the value back to Additem. How can I declare variable name in Additem.h in a way that all the members of class Review see it?
    Thank you.


  • Lifetime Qt Champion

    Hi,

    How are Review and Additem related ? What does each of these classes do ?



  • Well, I guess your class AddItem looks something like this:

    class Additem {
    public:
      QString name() const;
      void setName(const QString& name);
    private:
      QString name;
    }
    

    Review may then access and change it using the defined public methods, maybe like so:

    #include "Additem.h"
    
    void yourFancyMethod() {
      Additem item;
      QString itemName = item.name();     // << Here we read the name variable from Additem
      // ... Manipulate itemName ...
      item.setName(itemName);             // << Here we write the changed itemName back to the Additem object
    }
    

    By the way, this is one of the key concepts of object oriented programming: If you want to change the properties of objects, you do this via nicely defined interfaces, and do not manipulate their properties directly.
    If you are unsure about this, I recommend you read up on that, have a look at some tutorials on object oriented programming. Else managing your code will get pretty tedious the bigger it gets.



  • @SGaist
    Additem is a form and Review is where the user can review the information entered in Additem. If there is an error Review sends the information back to Additem for the user to fix it.


  • Lifetime Qt Champion

    By error do you mean an invalid input ?



  • Hi @SGaist
    yes, error means invalid input.


  • Lifetime Qt Champion

    In that case, you shouldn't allow invalid input from the start. What kind of input are you giving to your users ?



  • @SGaist
    Hi,
    I was wrong. It is a catalog for collectibles. Review is supposed to give an option to the user to review the entries and if all entries correct are correct they can add itvto the database or if there is something to fix, it goes back to Additem where they can make changes.


  • Lifetime Qt Champion

    What kind of fixes do you have in mind ?



  • @SGaist
    Like they missed something, or made a wrong choice.


  • Lifetime Qt Champion

    AFAIU, these are not really errors in the sense of validation. Your user forgot to e.g. check an option in a multiple choice question but that doesn't count as "wrong" like he tried to put an invalid value. Thus I don't see the need to modify Additem back from Review.


Log in to reply