N
news.tkdsoftware.com
I have the following test code. What I have a question about is in
Func2Ref. In the pointer example, the last called method is actually the
one whom allocated memory for the object and returns the pointer to the
calling parent for it to be printed. In the reference example, the parent
actually creates the object but in Func2Ref, I need that object to be a
derived type. This is like how AST traversal occurs **hint**.
Can someone offer some input on how I should do this if I choose to use
&object reference instead of *object pointers??
class CNode {
public:
CNode() { }
virtual ~CNode() { }
virtual void print(void) = 0;
};
class CChildNode : public CNode {
public:
CChildNode() { }
virtual ~CChildNode() { }
};
class CBabyNode : public CChildNode {
public:
CBabyNode(int nVal) m_nVal(nVal) { }
virtual ~CBabyNode() { }
void print(void) { cout << m_nVal; }
private:
int m_nVal;
};
void Func2Ptr(CNode *node) {
node = new CBabyNode(5);
}
void Func1Ptr(CNode *node) {
Func2Ptr(node);
}
void Func2Ref(CNode &node) {
// here I need to be able to change
// CNode to a CBabyNode and be able
// to have it print its value when
// the main program calls print.
}
void Func1Ref(CNode &node) {
Func2Ref(node);
}
int main(int argc, char* argv[]) {
{
// Do pointer test
CNode *pNode = NULL;
Func1Ptr(pNode);
if(pNode != NULL) {
pNode->print();
delete pNode;
}
// Do Ref test
CNode node;
Func1Ref(node);
node.print();
return 0;
}
Thanks!
--
Func2Ref. In the pointer example, the last called method is actually the
one whom allocated memory for the object and returns the pointer to the
calling parent for it to be printed. In the reference example, the parent
actually creates the object but in Func2Ref, I need that object to be a
derived type. This is like how AST traversal occurs **hint**.
Can someone offer some input on how I should do this if I choose to use
&object reference instead of *object pointers??
class CNode {
public:
CNode() { }
virtual ~CNode() { }
virtual void print(void) = 0;
};
class CChildNode : public CNode {
public:
CChildNode() { }
virtual ~CChildNode() { }
};
class CBabyNode : public CChildNode {
public:
CBabyNode(int nVal) m_nVal(nVal) { }
virtual ~CBabyNode() { }
void print(void) { cout << m_nVal; }
private:
int m_nVal;
};
void Func2Ptr(CNode *node) {
node = new CBabyNode(5);
}
void Func1Ptr(CNode *node) {
Func2Ptr(node);
}
void Func2Ref(CNode &node) {
// here I need to be able to change
// CNode to a CBabyNode and be able
// to have it print its value when
// the main program calls print.
}
void Func1Ref(CNode &node) {
Func2Ref(node);
}
int main(int argc, char* argv[]) {
{
// Do pointer test
CNode *pNode = NULL;
Func1Ptr(pNode);
if(pNode != NULL) {
pNode->print();
delete pNode;
}
// Do Ref test
CNode node;
Func1Ref(node);
node.print();
return 0;
}
Thanks!
--