CHAPTER 13

image

Constructor

In addition to fields and methods, a class can contain a constructor. This is a special kind of method used to construct, or instantiate, the object. It always has the same name as the class and does not have a return type. To be accessible from another class the constructor needs to be declared in a section marked with the public access modifier.

class MyRectangle{  public:    int x, y; MyRectangle();};MyRectangle::MyRectangle() { x = 10; y = 5; }

When a new instance of this class is created the constructor method will be called, which in this case assigns default values to the fields.

int main(){    MyRectangle s;}

Get C++ 14 Quick Syntax Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.