c++ initialize member object in constructor code example

Example 1: c++ class member initialization

class Test  {
private:
  std::string data;
public:
  test(std::string data) : data(data) {}
  std::string getData() {
    return data;
  }
};

int main() {
  Test test("This is just some random Text");
  std::cout << test.getData() << std::endl;
  return 0;
}

Example 2: 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) {
// Code here
}

Tags:

C Example