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
- struct vs class When to Use Each
- Member Variables and Methods
- Constructors and Member Initializer Lists
- The this Pointer and Encapsulation