C++ Class Default Constructor Example
A default constructor in C++ is a special member function that is automatically called when an object of a class is created without any arguments. It provides a way to initialize the member variables of the object with default values.
Here is an example of a C++ class with a default constructor:
#include
class Rectangle {
public:
// Default constructor
Rectangle() {
width = 0;
height = 0;
}
// Member functions
int getArea() {
return width * height;
}
private:
int width;
int height;
};
int main() {
// Create a Rectangle object using the default constructor
Rectangle rect;
// Print the area of the rectangle
std::cout << "Area of the rectangle: " << rect.getArea() << std::endl;
return 0;
}
Explanation:
- Class Declaration: We define a class named
Rectangle
with private member variableswidth
andheight
. - Default Constructor: The default constructor is defined as
Rectangle()
. It initializes thewidth
andheight
to 0. - Member Function: The
getArea()
function calculates the area of the rectangle. - Object Creation: In the
main
function, we create an object ofRectangle
namedrect
. Since we don't pass any arguments, the default constructor is called automatically. - Output: The code prints the area of the rectangle, which is 0 because both width and height are initialized to 0 by the default constructor.
Benefits of Default Constructors:
- Initialization: Ensures that all member variables are initialized with a default value.
- Object Creation: Allows you to create objects without explicitly providing values for all member variables.
- Consistency: Provides a consistent starting point for objects of a class.
Note:
- If a class does not define any constructors, the compiler will automatically generate a default constructor for you. This constructor will not initialize the member variables, so they will have undefined values.
- You can define multiple constructors in a class, but only one can be a default constructor (the one that takes no arguments).
The default constructor is a fundamental part of C++ object-oriented programming and is essential for ensuring proper initialization of class objects.