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?
CodePudding user response:
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;
}
};
CodePudding user response:
What you need is to provide proper constructors, member variables (and possibly getters).
Or you need to add a setter to a and use m_a.set_value(42)
.
#include <iostream>
class A
{
public:
// constructor for A with a value.
// made explicit to avoid implicit type conversions from int to A
explicit A(int value) :
m_value{ value }
{
};
int get_value() const noexcept
{
return m_value;
}
private:
int m_value;
};
class B
{
public:
B(int value) :
m_a{ value } // <-- this will pass value on to the constructor of A
{
};
const A& get_A() const noexcept // not good design, for educational purposes only
{
return m_a;
}
private:
A m_a;
};
int main()
{
B b{ 42 };
std::cout << b.get_A().get_value();
return 0;
}