ambuli
asked on
Inheritance design question
Hi Experts,
I have the following problem.
#include <iostream>
#include <string>
using namespace std;
class M{};
class N{};
class A{
};
class B: public A
{
private:
M m_memM;
};
class C: public A
{
private:
N m_memN;
};
int main()
{
return 0;
}
In the code snippet above, class B, C are derived from class A.
For B, it should have a member of class M
For class C, it should have a member of class N. That is, the derived classes of A differ by their member. class M, class N are not related.
The way, I defined above seem not to work. The reason being parent class not being able to access membes of derived class. It was pointed out in one of my earlier question and after some testing I found that is what happening.
So, I had to move the members as below.
class A{
protected:
M m_memM;
N m_memN;
};
class B: public A
{
private:
};
class C: public A
{
private:
};
But, I smell that having member variables that will be used by some derivation of the parent class is not a good design. Is it so? How can I prevent this?
(The problem is related to my previous question on void pointers).
I have the following problem.
#include <iostream>
#include <string>
using namespace std;
class M{};
class N{};
class A{
};
class B: public A
{
private:
M m_memM;
};
class C: public A
{
private:
N m_memN;
};
int main()
{
return 0;
}
In the code snippet above, class B, C are derived from class A.
For B, it should have a member of class M
For class C, it should have a member of class N. That is, the derived classes of A differ by their member. class M, class N are not related.
The way, I defined above seem not to work. The reason being parent class not being able to access membes of derived class. It was pointed out in one of my earlier question and after some testing I found that is what happening.
So, I had to move the members as below.
class A{
protected:
M m_memM;
N m_memN;
};
class B: public A
{
private:
};
class C: public A
{
private:
};
But, I smell that having member variables that will be used by some derivation of the parent class is not a good design. Is it so? How can I prevent this?
(The problem is related to my previous question on void pointers).
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Since you are using void pointers (from your previous Q http:/Q_22062544.html) then why not just coerce the pointer a B* or a C* (rather than an A*)?? That should let you access the desired members.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.