I am probably missing something very simple, but I’ll be very grateful if someone can point me in the right direction.
I have 2 classes: A and B. A has a collection of data structures and functions that modify them (for a hypothetical example, say add, delete, insert, etc to the data structures). B has a collection of functions that specify how the data structures are modified in A.
For the sake of extensibility, B is inherited to reflect different possible behaviors on A’s data structures. One implementation of B may choose to add to the beginning of A’s data structure, delete from the end, and so on. Another implementation might add to the end, delete from the beginning, and so on.
I am passing an object of base class B during the creation of A, so that the generic addNode(), deleteNode(), and other functions of A can actually look up the particular type of B object passed to it during creation and refer to its implementation in B as to what action to follow.
In this hypothetical example below, the data structure in concern is a doubly linked list. In my problem, the data structure itself is not the issue. I am concerned about how to call the correct method in derived class of B to modify my data structure in A.
Class A:
class A
{
static A create(B bObj); // returns an A object after calling the constructor
void addNode(int);
void deleteNode();
...
private:
struct myNode
{
int value;
myNode *next;
myNode *prev;
}
myNode *head;
myNode *tail;
}
Class B:
class B
{
virtual void addNode(int);
virtual void deleteNode();
...
}
Class ChildB1:
class ChildB1
{
void addNode(int)
{
// code for add to the front
}
void deleteNode()
{
// code for delete from the back
}
}
Class ChildB2:
class ChildB2
{
void addNode(int)
{
// code for add to the back
}
void deleteNode()
{
// code for delete from the front
}
}
The problem I am running into is how to give a child class of B access to the current object of A I am operating on? Let’s say, while creation of the object of A (aObj) with the create() method, I passed a reference to object ChildB2.
B *bObj = new ChildB2();
A aObj = A.create(*bObj);
Now when I call aObj.add(), I want it to call the add() method of ChildB2 class, so that it can operate on the linked list in A and add it to the back end of the list. But how does the add() function of ChildB2 class access the linked list of aObj?
I apologize if the question is long-winded and naive. I am happy to give further clarification if required.
Add
Bas a friend ofA.Since friendship is not inherited,
Bhas to explicitly provide its heirs with access toAprivate parts.A couple of notes: you should pass
Btocreateby reference, not by value, otherwise yourChildB2object will be sliced. You also need to manageBs lifetime somehow.