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

Creating a public variable from another class (C++)

If you have two classes, class a and class b, could you create a variable in class a from class b?
main.cpp

class A {
    public:
        A() {}
};

class B {
    public:
        B() {
            test = A();
            test.<variable name> = <variable value>;
        }
};

The code above is just an example. It will probably cause an error.

"variable name" doesn’t exist in class A. Is there a way to create this variable for class A in the constructor for class B?

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 :

No, C++ is not Javascript. Types are strict and, after you define a type, there’s no way to modify it.

You can, however, create a local type in a function:

class B {
public:
    B() {
        struct A_extended : A {
            int i;
        };
        auto test = A_extended();
        test.i = 1;
    }
};
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