Constructors

Hey guys, how do i make a constructor/ destructor to a class inside a class?

for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
         h.file
  class MonomList{
private:
	class Node{
	public:
		Monom *mon;
		Node *next;
		Node *prev;
	};
	Node *head;
	Node *tail;
};

end of h.file

this is my class, how can i make a constructor to Node?


First why do you have Node defined inside your class?

Second if you want to do this the I suggest you create your constructor in the definition.

Jim
Defining the constructor inside the class body.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MonomList{
private:
	class Node{
	public:
		Node(){
			// Put code here.
		}
		Monom *mon;
		Node *next;
		Node *prev;
	};
	Node *head;
	Node *tail;
};


Defining the constructor outside the class body.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MonomList{
private:
	class Node{
	public:
		Node();
		Monom *mon;
		Node *next;
		Node *prev;
	};
	Node *head;
	Node *tail;
};

MonomList::Node::Node(){
	// Put code here.
}
Last edited on
First why do you have Node defined inside your class?


It's a node of a MonomList. Having the class be within the scope of the MonomList class makes perfect sense.

+1 to Peter87's solution(s).
closed account (D80DSL3A)
Nice basic solution Peter87.
Of course, I must go overboard.
Having a Monom* as a data member in the Node suggests polymorphic storage (else why not store a Monom instance), which in turn suggests having a virtual clone() method returning a pointer to a new Monom object of the appropriate type (as a copy). While we're at it, why not establish all linkage within the list as well?

1
2
3
4
5
Node( const Monom& r_mon, Node* Prev, Node* Next ): mon( r_mon.clone() ), prev(Prev), next(Next)
{
    if( prev ) prev->next = this;
    if( next ) next->prev = this;
}


EDIT: @ne555. Good points.
Last edited on
> Having a Monom* as a data member in the Node suggests polymorphic storage
> (else why not store a Monom instance)
Because you are not responsible of the lifetime.
Because you don't want to work with a copy.

(use a smart pointer to resolve node copies and validity of access to mon)
Topic archived. No new replies allowed.