Search code examples
c++qtqt-creatorqwidgetqdialog

How to access the value of another class in current working class


Parent class : parentClass.h

class parentClass : public QWidget
{
    Q_OBJECT

public:
    QString nextFollowUpDate;   //I want to access this variable from child class

}

Parent class : parentClass.cpp

// accessing child 

childClass*objcalender = new childClass();
objcalender->show();

Child class : childClass.h

class childClass : public QWidget
{
    Q_OBJECT

public:
    childClass();
}

Child class : childClass.cpp

#include parentClass .h

parentClass *myFollowUp = qobject_cast<parentClass*>(parent());

//object of myFollowUp is not created and program get terminated by showing exception 

parentClass->nextFollowUpDate = selectedDate;   //can not access this variable

Solution

  • Two things. First, if you want to access a member function or variable of class from another class you have to create an object of the class you want to acess and then just use "->" or "." to access it. Something like this:

    ParentClass* parentObjPtr = new ParentClass(); //not mandatory to use the new() operator, but it has always better to reserve the memory space
    parentObjPtr->varName = "hello";
    //OR
    ParentClass parentObj = new ParentClass();
    parentObj.functionName = "hello";
    

    But if for some reason you don't plan on creating objects of that class, you can always make the members you want to access "static":

    class parentClass: public QWidget
    {
    
    Q_OBJECT
    
    public:
    
    static QString nextFollowUpDate;
    
    }
    

    And then do this to access that member variable:

    ParentClass::nextFollowUpDate = "hello";
    cout << "Content of nextFollowUpDate: " << ParentClass::nextFollowUpdate << endl;
    

    Also, if you plan on using that class a lot but dont want to keep typing "ParentClass::" in your code, you can define a namespace for that class next to your includes:

    #include "ParentClass.h"
    using namespace ParentClass;
    ----ETC----
    ----ETC----
    
    int main(){
    nextFollowUpDate = "hello"; //because we defined a namespace for that class you can ommit the "ParentClass::"
    cout<<nextFollowUpDate<<endl;
    }