member initialization list c++ code example

Example 1: member initializer list in c++

// Constructor Member Initializer List

#include <iostream>

class Example
{
private:
    int x, y;

public:
    Example() : x(0), y(0) {}
    Example(int x1, int y1) : x(x1), y(y1) {}
    ~Example() {}
};

int main()
{
    Example e;
}

Example 2: initialization list c++

struct S {
    int n;
    S(int); // constructor declaration
    S() : n(7) {} // constructor definition.
                  // ": n(7)" is the initializer list
};

S::S(int x) : n{x} {} // constructor definition. ": n{x}" is the initializer list

int main() {
    S s; // calls S::S()
    S s2(10); // calls S::S(int)
}

Example 3: c++ class member initializer list

#include <iostream>
class Entity {
private : 
	std::string m_Name;
	int m_Score;
	int x, y, z;
public:
	Entity()
		:m_Name("[Unknown]"),m_Score(0),x(0),y(0),z(0)//initialize in the order of how var are declared
	{
	}
	Entity (const std::string& name) 
		:m_Name(name)
	{}
	const std::string& GetName() const { return m_Name; };
};
int main()
{
	Entity e1;
	std::cout << e1.GetName() << std::endl;
	Entity e2("Caleb");
	std::cout << e2.GetName() << std::endl;
	std::cin.get();
}

Example 4: initializer list c++

class Example {
public:
	int m_A, m_B, m_C;
	Example(int a, int b, int c);
};

Example::Example(int a, int b, int c):
	// This is an initializer list
	m_A(a),
	m_B(b),
	m_C(c)
{ /* Constructor code */ }

Example 5: c++ initialization list

class Something
{
private:
    int m_value1;
    double m_value2;
    char m_value3;
 
public:
    Something()
    {
        // These are all assignments, not initializations
        m_value1 = 1;
        m_value2 = 2.2;
        m_value3 = 'c';
    }
};

Tags:

Cpp Example