c++ create object with constructor 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) {
// Code here
}

Example 2: cpp class constructor

class MyClass {     // The class
  public:           // Access specifier
    MyClass() {     // Constructor
      cout << "Hello World!";
    }
};

Example 3: formats of constructor in c++

Line::Line( double len): length(len) {
   cout << "Object is being created, length = " << len << endl;
}

Tags:

C Example