Constructors

Default, parameterized, and copy constructors

Interview Relevant: Object initialization

Constructors

Special methods that initialize objects.

Code Examples

Various constructor types and initialization.

cpp
1class Rectangle {
2    int width, height;
3
4public:
5    // Default constructor
6    Rectangle() : width(0), height(0) {}
7
8    // Parameterized constructor
9    Rectangle(int w, int h) : width(w), height(h) {}
10
11    // Copy constructor
12    Rectangle(const Rectangle& other)
13        : width(other.width), height(other.height) {}
14
15    // Move constructor
16    Rectangle(Rectangle&& other) noexcept
17        : width(other.width), height(other.height) {
18        other.width = other.height = 0;
19    }
20
21    // Delegating constructor (C++11)
22    Rectangle(int size) : Rectangle(size, size) {}
23};
24
25// Initialization
26Rectangle r1;              // Default
27Rectangle r2(10, 20);      // Parameterized
28Rectangle r3 = r2;         // Copy
29Rectangle r4{5, 10};       // Uniform init (C++11)
30Rectangle r5 = Rectangle(3, 4);  // Direct
31
32// Explicit prevents implicit conversion
33class Explicit {
34    explicit Explicit(int x) {}
35};
36// Explicit e = 10;  // Error!
37Explicit e(10);     // OK

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In