Inheriting and using class data members

In the code below, class D1 inherits from class A.

A has a virtual function and a data member FileCount. So D1 inherits both.

I am keeping the interface implementation unchanged for D1, however for data member FileCount, I'd like to use a different value for D1 than the base class.

Is it possible to do that?

Compiling and running below code, displays:

0
Inside Base class
0
Inside Base class


I need to see below as output:

0
Inside Base class
100
Inside Base class

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
class A
{
public:
         int FileCount;

	A() 
	{
		FileCount = 0;
	}

	virtual void VerifyInventoryData() const
	{
		cout << FileCount<< endl;
		cout << "Inside Base class" << endl;
	}
};

class D1 : public A
{
public:
	int FileCount;

	D1()
	{
		FileCount = 100;
	}

};

int main()
{
	A* pA = new A;

	A* pD = new D1;

	pA->VerifyInventoryData();

	pD->VerifyInventoryData();

}
In OO, you shouldn't think about inheriting data. You should think about the virtual functions.

To achieve the effect you want, D1 must provide an implementation for VerifyInventoryData().
1
2
3
4
5
6
7
8
9
10
class D1 : public A
{
public:
	int FileCount; //this is another member. It's hiding the one inherited

	D1()
	{
		FileCount = 100;
	}
};

To achieve the effect you want, D1 must provide an implementation for VerifyInventoryData().
¿and do what?

However you should not care about members of the parent class. It introduces an even higher coupling.
You should let the parent to handle it. ¿what it is used for?
@kbw - What if VerifyInventoryData()'s implementation is same for the entire hierarchy - you don't need to define VerifyInventoryData() for D1 then, right?

@ne555 - Thanks for pointing it out - I removed D1::FileCount. I did figure out what I missed.

Here's what I needed to do, in order to get results as I needed:

1
2
3
4
5
6
7
8
9
class D1 : public A
{
public:
	D1()
	{
		A::FileCount = 100;
	}

};

Topic archived. No new replies allowed.