Search code examples
c++classinheritancefunction-definition

Access variable from another class (in C++)


This may be a really easy question but... here it goes. (Thanks in advance!)

I am simplifying the code so it is understandable. I want to use a variable calculated inside another class without running everything again.

source.ccp

#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
    beginclass BEGINOBJECT;

    BEGINOBJECT.collectdata();
    cout << "class " << BEGINOBJECT.test;

    calculationclass SHOWRESULT;
    SHOWRESULT.multiply();

    system("pause");
    exit(1);
}

begin.h

#include <iostream>
using namespace std;

#ifndef BEGIN_H
#define BEGIN_H

class beginclass
{
    public:
        void collectdata();
        int test;
};

#endif

begin.cpp

#include <iostream>
#include "begin.h"

void beginclass::collectdata()
{
    test = 6;
}

calculation.h

#include <iostream>
#include "begin.h"

#ifndef CALCULATION_H
#define CALCULATION_H

class calculationclass
{
    public:
        void multiply();
};

#endif

calculation.cpp

#include <iostream>
#include "begin.h"
#include "calculation.h"

void calculationclass::multiply()
{
    beginclass BEGINOBJECT;
    // BEGINOBJECT.collectdata(); // If I uncomment this it works...
    int abc = BEGINOBJECT.test * 2;
    cout << "\n" << abc << endl;
}

Solution

  • Simply define member function multiply as

    void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
    {
        int abc = BEGINOBJECT.test * 2;
        cout << "\n" << abc << endl;
    }
    

    And call it as

    int main()
    {
        beginclass BEGINOBJECT;
    
        BEGINOBJECT.collectdata();
        cout << "class " << BEGINOBJECT.test;
    
        calculationclass SHOWRESULT;
        SHOWRESULT.multiply( BEGINOBJECT );
    
        system("pause");
        exit(1);
    }