c++ class constructor initialization code example
Example 1: how to initialize the object in constructor in c++
BigMommaClass {
BigMommaClass(int, int);
private:
ThingOne thingOne;
ThingTwo thingTwo;
};
BigMommaClass::BigMommaClass(int numba1, int numba2): thingOne(numba1 + numba2), thingTwo(numba1, numba2) {
}
Example 2: 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)
{
}
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();
}