I have two structs pins1_t
& pins2_t
with the same field names but different values. pins2_t
is derived from pins1_t
namespace pins {
struct pins1_t {
int A = 1;
int B = 2;
int C = 3;
int D = 4;
};
struct pins2_t : pins1_t {
int A = 6;
int B = 7;
int C = 8;
int D = 9;
};
};
I'm trying to access the values from pins2_t
by referencing via the base struct, but without any success.
pins::pins1_t pins1;
pins::pins2_t pins2;
pins::pins1_t* pPins;
pins::pins1_t* pPins2;
pPins = &pins1;
pPins2 = &pins2;
print("Pins %d, Pins2 %d, PPins %d, PPins2 %d", pins1.A, pins2.A, pPins->A, pPins2->A);
The output is: "Pins 1, Pins2 6, PPins 1, PPins2 1"
But should be: "Pins 1, Pins2 6, PPins 1, PPins2 6"
Even if I try pins::pins2_t* pPins2
, so I reference the derived class pointer with the derived class I get the value of the base class :/
The members in your derived class shadow the members in your base class. This is almost never what you want (since, as you noticed, it doesn’t work).
Since these are just variables anyway, there’s no need to shadow the declarations in the child class. Just initialise the base class members:
struct pins1_t {
int A = 1;
int B = 2;
int C = 3;
int D = 4;
};
struct pins2_t : pins1_t {
pins2_t() : pins1_t{6, 7, 8, 9} {}
};
(Alternatively, you could employ runtime polymorphism via virtual functions as suggested by interjay, but there’s currently nothing in your question to suggest that this is necessary; and in the absence of a compelling reason it’s over-engineering.)