Skip to content

Instantly share code, notes, and snippets.

@BenEmdon
Created April 19, 2017 21:49
Show Gist options
  • Save BenEmdon/e2283193fb57f717079c5153fa4d56db to your computer and use it in GitHub Desktop.
Save BenEmdon/e2283193fb57f717079c5153fa4d56db to your computer and use it in GitHub Desktop.
A brief overview of member initializer syntax in C++

C++ Member Initializer Syntax

Member initializer syntax is a great way to give data members initial values on object initialization.

"All other things being equal, your code will run faster if you use initialization lists rather than assignment." - isocpp.org

For the purposes of this example let's pretend we have the class Cat:

#include <iostream>
#include <string>
using namespace std;

class Cat {
public:
    // following the initializer's signature after the `:` is the member initializer list
    Cat(string name = "unnamed", int age = 0): name(name), age(age) { }
    const string name;
    int age;
};

And the object is created just as expected:

Cat cat = Cat("Cat-Man", 5);
cout << cat.name << endl; // "Cat-Man"
cout << cat.age << endl; // "5"

For more information definitely take a look at: Why you should, in most cases, initialize all member objects in the member initialization list

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