0Pricing
C++ Academy · Lesson

Constructors and Member Initializer Lists

Initialize members cleanly using member initializer lists.

What is a Constructor?

A constructor is a special method that runs when an object is created. It has the same name as the class and no return type.

class Point {
public:
    Point() {              // default constructor
        x_ = 0;
        y_ = 0;
    }
private:
    int x_, y_;
};

Parameterized Constructors

Constructors can take parameters and you can have several overloads.

class Point {
    int x_, y_;
public:
    Point() : x_(0), y_(0) {}
    Point(int x, int y) : x_(x), y_(y) {}
};

All lessons in this course

  1. struct vs class When to Use Each
  2. Member Variables and Methods
  3. Constructors and Member Initializer Lists
  4. The this Pointer and Encapsulation
← Back to C++ Academy