chpicker
Programmer
- Apr 10, 2001
- 1,316
How do you write a copy constructor for a class that contains a member variable which is a pointer to a polymorphic base class? Here's a snapshot of the relevant classes. It's a linked list class:
How do I go about coding the copy constructors for headnode and datanode? The Linked List itself is what will be copied in my code when I pass the whole list by value to my function. (Yes, I have to pass it by value. This is very important.)
The LinkedList class creates a new headnode by passing the original. I think I did that right. The headnode's copy constructor then needs to duplicate the pNext node, but it's a node pointer that could be pointing to either a datanode or a tailnode. The datanode class has the same problem. How do you code that? I know it's possible to switch on the runtime type of the pointer, but I don't know how to do it, and I've heard it's a sign of poor class design to resort to that process anyway.
Is there some way to code a copy constructor for the base node class that will take a subclass reference as a parameter and create the right object? That doesn't sound possible to me, as "new node" only allocates enough memory for a node, not a headnode.
What can I do here? How do you code a copy constructor for a class with polymorphic pointers as member variables?
Ian
Code:
class node {
public:
node();
~node();
};
class headnode:public node {
public:
headnode() {pNext=new tailnode;}
headnode(const headnode& rhs);
~headnode() {delete pNext};
private:
node* pNext;
};
class datanode:public node {
public:
datanode(data* theData,node* next):pData(theData),pNext(next) {}
datanode(const datanode& rhs);
~datanode() {delete pData; delete pNext;}
private:
node* pNext;
data* pData;
};
class tailnode:public node {
public:
tailnode() {}
tailnode(const tailnode& rhs);
~tailnode() {}
};
class LinkedList {
public:
LinkedList() {pHead=new headnode;}
LinkedList(const LinkedList& rhs) {pHead=new headnode(*(rhs.pHead));
~LinkedList() {delete pHead;}
private:
headnode* pHead;
};
The LinkedList class creates a new headnode by passing the original. I think I did that right. The headnode's copy constructor then needs to duplicate the pNext node, but it's a node pointer that could be pointing to either a datanode or a tailnode. The datanode class has the same problem. How do you code that? I know it's possible to switch on the runtime type of the pointer, but I don't know how to do it, and I've heard it's a sign of poor class design to resort to that process anyway.
Is there some way to code a copy constructor for the base node class that will take a subclass reference as a parameter and create the right object? That doesn't sound possible to me, as "new node" only allocates enough memory for a node, not a headnode.
What can I do here? How do you code a copy constructor for a class with polymorphic pointers as member variables?
Ian