Inheritance question: Use parent's function on child's data?

Inheritance question: How to inherit a parent's function and use it on the children's data?

The example below shows what I am trying to accomplish.
It does not work as is, but it works if the puts() function is moved to the child classes.

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
#include <iostream>
using namespace std;

class Parent
{
    public:
	void puts() { cout << " array[1]=" << array[1]; };
	// error: 'array' was not declared in this sope
};

class Child1: public Parent
{
    public:
	static const char array[];
};

class Child2: public Parent
{
    public:
	static const char array[];
};

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

Child2 obj2;
const char Child2::array[2] = {'1', '2'};

int main()
{
	obj1.puts();
	obj2.puts();
}

Thank you.
Last edited on
Can you make puts virtual in Parent and have each child class override it?
Thanks for the quick response.

Overriding puts() is not an option because then there would be multiple copies to puts() to maintain.

I was looking for a way for the Child classes to inherit puts().
I found a way to make the parent's puts() function accesses child's data.
This works:
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[2] = {'1', '2'};

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

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


Topic archived. No new replies allowed.