Skip to main content
gamedev.net
🔒 Locked

Constructor in constructor

Started by Gonzzor Feb 27, 2003 at 7:05 AM 2 replies 500+ views
Original Post
Gonzzor
Gonzzor
Hi... Have some problem with this piece of code
SPRITEBASE::SPRITEBASE(char *filename, int frames, bool bitmask = 0) {
	SPRITEBASE(); 
	Load(filename, frames, bitmask);
}
//Standard Construction
SPRITEBASE::SPRITEBASE() {
	m_Ok = false;
	m_SrcRect = new SDL_Rect;
	m_SrcRect->h = 0;
	m_SrcRect->w = 0;
	m_SrcRect->x = 0;
	m_SrcRect->y = 0;
}
 
The problem is that i CAN create a new SPRITEBASE object by calling (On 3 of 4 computers) SPRITEBASE* SpriteBase = new SPRITEBASE("file.png", 2, 0); But then when I try to create anohter SPRITEBASE object SPRITEBASE* SpriteBase2 = new SPRITEBASE("file.png", 2, 0); It crach when I try to do m_SrcRect->h = 5; But if I create them by this piece of code it works perfect: SPRITEBASE* SpriteBase = new SPRITEBASE(); SpriteBase->Load("file.png", 2, 0); SPRITEBASE* SpriteBase2 = new SPRITEBASE(); SpriteBase2->Load("file.png", 2, 0); Have solved the problem by using a third function that do the Init stuff, InitVars(), but why can''t I do it like this? Is there any limits or is it just me that are crazy enough to think that this should work?
If you don't want to learn anything you are in really bad trouble...
Qw3r7yU10p!
Qw3r7yU10p!

  SPRITEBASE::SPRITEBASE(char *filename, int frames, bool bitmask = 0)
: m_Ok(false), m_SrcRect(new SDL_Rect) {
Load(filename, frames, bitmask);
}
//Standard Construction

SPRITEBASE::SPRITEBASE()
: m_Ok(false), m_SrcRect(new SDL_Rect) {
}


the SDL_Rect constructor should set the values to zero for you.

the : m_Ok, etc is an initialisation list. It puts the values straight into the member variables as they are created rather than creating and then assigning to them, as you were doing.

You can''t call a constructor on an object. Either repeat the code (as above) or have an initZero function (which will be less efficient)
Gonzzor
Gonzzor
Hi..

Just what I thaught but I couldn''t figure out why it worked on 3 of 4 computers, with the same .exe...

But anyway thanks for straighting things out...
If you don't want to learn anything you are in really bad trouble...
civguy
civguy
quote:
Original post by petewood
It puts the values straight into the member variables as they are created rather than creating and then assigning to them, as you were doing.

[...] initZero function [...] will be less efficient
There''s no speed difference for basic types, since basic types aren''t default initialized (and both m_SrcRect and m_Ok seem like basic types to me). So I''d suggest using init()-function as it will be equally efficient (if inlined).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.