« Previous entry | Next entry » Browse > Snippets
Skip to comments (4)
Faster C++ class constructors
Posted by Erik on Jan 11 2006 @ 14:27 :: 1443 unique visits
If we have a class like this:CODE: CPP
class foo {
public:
foo() {
printf("foo\n");
}
};
public:
foo() {
printf("foo\n");
}
};
And a second class like this:
CODE: CPP
class bar {
public:
foo myfoo;
bar(foo _myfoo) {
myfoo = _myfoo;
}
};
public:
foo myfoo;
bar(foo _myfoo) {
myfoo = _myfoo;
}
};
And you would execute some code like this:
CODE: CPP
foo somefoo;
bar somebar(somefoo);
bar somebar(somefoo);
The first statement will obviously print "foo". But the second statement will also print "foo". This because before foo's copy constructor is implicitly called (myfoo = _myfoo), myfoo is initialized with it's normal constructor.
If you write bar's constructor like this:
CODE: CPP
bar(foo _myfoo) : myfoo(_myfoo) {
;
}
;
}
myfoo isn't initialized using the normal constructor but only with it's copy constructor. Thus writing constructors this way is faster because it executes less code. Ofcource this doesn't matter if myfoo is a First-class object like int or float, because these don't have normal constructors.
4 comments posted so far
Add your own »
2. On May 13 2009 @ 15:53 guest wrote:
Need Furniture? And need to buy furniture from China at competitive price? LongYear Furniture is your source for quality bedroom furniture featuring a huge selection of home furniture a happy home for beautiful life, kids furniture for a good memory of childhood, and to gain an extra good price from wholesale furniture and direct from furniture manufacturers China, styles of China furniture are available, living room furniture is also nice for your house, find dining room furniture and more!3. On Jul 14 2009 @ 07:33 guest wrote:
AVI to DVD Converter,AVI to DVD Creator,iPhone Ringtone Maker for Mac,AVI Converter OS X,VOB Converter OS X,AVCHD Video Converter,FLV Converter,PowerPoint Converter,AVCHD Converter,Blue-Ray ripper,Rip Blue Ray,FLV to MOV Mac,VOB to DVD,HD Video Converter,iPod Playlist Transfer4. On Jan 05 2010 @ 14:27 uggbaileybutton wrote:
bailey button uggs-ugg boots cheap
ugg boots uk
ugg classic
1. On Jan 12 2006 @ 20:22 Erik wrote:
One addition that has to do with C++ constructors.If you have a class with virtual functions, never use
to set all your members to 0. It will destroy your vtable and all your calls to your virtual functions will cause access violations.