C++ Class Constructors
Constructors are special member functions that are called automatically when an object of a class is created. In C++, constructors are used to initialize the data members of an object and to provide default values for class objects. In this article, we will explore the basics of C++ class constructors, including how to declare and define class constructors and how to use them to initialize objects of a class.
Declaring Class Constructors
To declare a class constructor, simply write a constructor function inside the class definition with the same name as the class. For example, consider the following code:
1class Rectangle { 2 int width, height; 3 public: 4 Rectangle() { 5 width = 0; 6 height = 0; 7 } 8};
In this example, we declare a class constructor Rectangle
that sets the width and height of a Rectangle
object to 0.
Defining Class Constructors
Constructors can be defined either inside or outside the class definition, just like class methods. To define a constructor inside the class definition, simply write the function definition inside the class body. To define a constructor outside the class definition, write the function prototype inside the class definition and the full function definition outside the class definition. For example, consider the following code:
1class Rectangle { 2 int width, height; 3 public: 4 Rectangle(); 5}; 6 7Rectangle::Rectangle() { 8 width = 0; 9 height = 0; 10}
In this example, we define the Rectangle
constructor outside the class definition using the syntax ClassName::ConstructorName()
.
Using Class Constructors to Initialize Objects
To use a class constructor to initialize an object of a class, simply create an object using the constructor. For example, consider the following code:
1#include <iostream> 2 3class Rectangle { 4 int width, height; 5 public: 6 Rectangle() { 7 width = 0; 8 height = 0; 9 } 10}; 11 12int main() { 13 Rectangle rect; 14 std::cout << "Width: " << rect.width << std::endl; 15 std::cout << "Height: " << rect.height << std::endl; 16 return 0; 17}
In this example, we create an object rect
of the Rectangle
class and use the constructor to initialize its data members. The output of this program will be:
1Width: 0 2Height: 0