« 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");
    }
};

And a second class like this:
CODE: CPP
class bar {
public:
    foo myfoo;

    bar(foo _myfoo) {
        myfoo = _myfoo;
    }
};

And you would execute some code like this:
CODE: CPP
foo 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 »

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
CODE: CPP
memset(this, 0, sizeof(classname));

to set all your members to 0. It will destroy your vtable and all your calls to your virtual functions will cause access violations.

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!

4. On Jan 05 2010 @ 14:27 uggbaileybutton wrote:

bailey button uggs

-ugg boots cheap

ugg boots uk

ugg classic

Add a new comment

Name:
Password: (leave empty for anonymous comment)
 
View formatting tags Comment: