Every class within the tree depends has-a relationship with other classes for monitoring voltage and current sensors (which are usually named 1,2,3...). The problem is that how many of these sensors there are depends on what type of unit is being simulated; meaning only the derived classes will know that.
#include <iostream>
class A {
public:
A() {};
virtual void Display() = 0;
protected:
int array[]; // size is purposefully left out in base class
};
class B : public A {
public:
B(int numbers[4]);
virtual void Display();
protected:
int array[4]; // 4 sensors are required, number fixed at compile time
}
B::B(int numbers[4]) {
for(int i=0; i<4; i++)
array[i] = numbers[i];
}
void B::Display() {
cout << " B numbers are: ";
for(int i = 0; i < 4; i++)
cout << array[i] << " ";
cout << endl;
}
class C : public A {
public:
C(int numbers[8]);
virtual void Display();
protected:
int array[8]; // 8 sensors needed, number fixed at compile time
};
C::C(int numbers[8]) {
for(int i=0; i<8; i++)
array[i] = numbers[i];
}
void C::Display() {
cout << " C numbers are: ";
for(int i = 0; i < 8; i++)
cout << array[i] << " ";
cout << endl;
}
This driver shows that this will technically work when using the g++ compiler, but I fear that I may have data hiding by redeclaring array in B and C classes.
main() {
int B_numbers[] = {1,2,,3,4};
int C_numbers[] = {5,6,7,8,9,10,11,12};
B b(B_numbers[]);
C c(C_numbers[]);
b.Display();
c.Display();
}
And thank you for any suggestions anyone is able to provide.
Nothing in any of the code you displayed uses A::array
, so you can just remove it as being unnecessary. B
and C
just have their own personal arrays that their respective overrides of Display()
know what to do with - A
doesn't need to be involved here. Just have:
struct A {
virtual void Display() = 0;
};
Note that B(int numbers[4]);
isn't actually any different from B(int *numbers)
as far as constructors go, the number there is just giving the illusion of safety - I can easily pass wrong-sized arrays into there. For that reason, prefer to use std::array
- which has the added benefit of being copy-constructible:
class B : public A {
public:
B (std::array<int, 4> const& arr)
: array(arr)
{ }
virtual void Display();
protected:
std::array<int, 4> array;
}