Pass data from child to parent?

The following inheritance example works for the application I am working on.
The parent gets the child's data via getElement() function.
But each child has an identical copy of getElement().
I want one copy of getElement() shared by all the children.
The arrays in the Child classes are of the same type and dimensions, only the content is different.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace std;

class Parent
{
    public:
	void puts();
	virtual char getElement(int)=0;
};

class Child1: public Parent
{
    public:
	static const char array[];
	char getElement(int index) { return array[index]; }
};

class Child2: public Parent
{
    public:
	static const char array[];
	char getElement(int index) { return array[index]; }
};

Child1 obj1;
const char Child1::array[3] = {'a', 'b', 'c'};

Child2 obj2;
const char Child2::array[3] = {'x', 'y', 'z'};

void Parent::puts()
{
	cout << " element[1]=" << getElement(1);
};

int main()
{			// output:
	obj1.puts();	// element[1]=b
	obj2.puts();	// element[1]=y
}

I tried defining getElement() in the Parent class so the children would inherit getElement(), but the compiler said "error: 'array' was not declared in this scope"

Is there a way to pass data from child to parent without multiple copies of an accessor?
Last edited on
I understand part of what you are doing, and I certainly understand why the compiler complains. It's because the parent doesn't know anything about a child and shouldn't. You could either do this:
1
2
3
4
5
6
7
class Parent
{
protected:
    static const char array[3];
public:
    char getElement(int index) { return array[index]; }
};


or you could do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Parent
{
public:
    char getElement(int index) = 0; // This forces a child to implement this function.  
                                    // Otherwise there's a compiler error
};

class Child1 : public Parent
{
private:
    static const char array[3];
public:
    char getElement(int index) { return array[index]; }
};
Last edited on
Topic archived. No new replies allowed.