Skip to content

These are the member initialiser lists not only used for the syntax also for the performance of not creating other non wanted object#9

Open
Butcher3Years wants to merge 1 commit intoMutable--keywordfrom
Member--Initialaizer-lists
Open

These are the member initialiser lists not only used for the syntax also for the performance of not creating other non wanted object#9
Butcher3Years wants to merge 1 commit intoMutable--keywordfrom
Member--Initialaizer-lists

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

Member Initializer Lists in C++ – Why They Matter

Member initializer lists are the preferred and often only correct way to initialize class members and base classes in a constructor.

Syntax

class Entity {
private:
    std::string name;
    int         score;
    Example     component;   // some other class

public:
    // Best practice: use initializer list
    Entity(const std::string& n, int s)
        : name(n)              // direct construction
        , score(s)
        , component(42)        // calls Example(int)
    {
        // constructor body – only for logic that can't go in init list
    }
};

Key Advantages

Direct initialization (not assignment) → avoids double construction
→ No unnecessary default constructor call + assignment
Required in these cases (you cannot do it in the body):
const members
Reference members
Members without default constructor
Base class constructors with arguments

More efficient – especially for types that are expensive to default-construct + assign
(e.g. std::string, std::vector, custom classes with allocations)
Guaranteed order of initialization: follows declaration order in the class (not the order in the list)
Cleaner code – constructor body stays focused on logic, not setup

…lso for the performance of not creating other non wanted object

classes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant