Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a function to access and edit objects from multiple classes

I am attempting to use objects from two classes in an outside function that I can call into main. I want this function to use methods to access and edit the objects as well

#include <iostream>

using namespace std;

class Test
{
    private:
        int attrib;
        
    public:
        int getAttrib();
        void setAttrib(int);
        
        Test();
        
        //Test *object;
};

Test::Test()
{
    attrib = 0;
}

int Test::getAttrib()
{
    return attrib;
}

void Test::setAttrib(int _attrib)
{
    attrib = _attrib;
    cout << endl << "Test set opened" << endl;
}

class Test2
{
    private:
        char character;
        
    public:
        char getCharacter();
        void setCharacter(char);
        
        Test2();
        
        //Test2 *object2;
};

Test2::Test2()
{
    character = 'a';
}

char Test2::getCharacter()
{
    return character;
}

void Test2::setCharacter(char _character)
{
    character = _character;
    cout << endl << "Test2 set opened" << endl;
}

void setting(Test object, Test2 object2)
{
    cout << endl << "Success" << endl;
    
    object.setAttrib(1);
    object2.setCharacter('A');
    
    cout << object.getAttrib() << endl;
        cout << object2.getCharacter() << endl;
}

int main()
{
    Test object;
    Test2 object2;
    
    cout << "Construct: " << object.getAttrib() << " " << object2.getCharacter() << endl;
    
    setting(object, object2);
    
    cout << endl;
    
    cout << "Function: " << object.getAttrib() << " " << object2.getCharacter() << endl;
    
    object.setAttrib(2);
    object2.setCharacter('b');
    
    cout << endl;
    
    cout << "Method: " << object.getAttrib() << " " << object2.getCharacter() << endl;
    
    return 0;
}

Right now the program outputs the objects and they change in the function, but the objects do not change outside of the function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should make sure that objects change not only in the settings function:

void setting(Test &object, Test2 &object2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading