Functions inside the structs or outside?

Started by
2 comments, last by dudedbz1 18 years, 6 months ago
Hello, I wonder wether there is any peformence diffrence between init function inside the node or outside it. In the final outcome this is about much bigger init functions. What will take up less ram? I assume making 500 MyNode's won't take up memory for 500 init functions? I just have to be sure :) Maybe this also matters, I use a deque for these nodes. deque<MyNode> Nodes; Init function inside the node

struct MyNode
{
	public:	
		char *x;
		MyNode()
		{
		 x = new char[25];
		}
	private:		
};

int main(void)
{
	MyNode *x = new MyNode();
}


Or init function outside the node.

struct MyNode
{
	public:	
		char *x;
		MyNode()
		{
		 // Nothing in here...
		}
	private:		
};

MyNode *CreateNode()
{
	MyNode *x = new MyNode;
	x.x = new char[25];
	return x;
}

int main(void)
{
	MyNode *x = CreateNode();
}


Thanks, - Myth
Advertisement
I'm not really sure about this, but is this even correct:
Quote:MyNode *x = new MyNode();


Doesnt it have to be like:
MyNode *x = new MyNode;


As far as I know, the constructor is called automatically for you.

Edit: Ok... I was wrong. But wont this:
Quote:
struct MyNode{	public:			char *x;		MyNode()		{		 x = new char[25];		}	private:		};


create a memory leak? That is, unless you delete it yourself from main since its public.
-----------------------------....::::DRAGON BALL Z::::....C<<"+"<<"+"; // Go C++ !!!-----------------------------
Nope, member functions are stored per class, not per instance. That means that they'll take up the same space whether they're member functions or not. The only difference between a member function and a static function is member functions get the this parameter implicitly.

In this case, since its a constructor, I highly suggest you keep it in the struct, since it should be called whenever you instantiate a node. It'll keep the code less obfuscated.

And dudedbz1 is right - you need to create new nodes with new Node()
When it comes to the functions, I agree. Being members or not they're functions. Again, as Mushu said, the only real difference is that the member functions will be able to access all the members without trouble, while not member functions will most likely need parameters.

P.S. Excuse me if I'm wrong, but wont a function outside of the class declared as a
friend
function of the class be also able to access all the members?

Edit: Typo ;).
-----------------------------....::::DRAGON BALL Z::::....C<<"+"<<"+"; // Go C++ !!!-----------------------------

This topic is closed to new replies.

Advertisement