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?
>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;
}
};