In C++, a constructor is a special member function of a class that gets called automatically when an object of the class is created. Its primary purpose is to initialize the data members of the class.
C++ supports different types of constructors based on the number of arguments and the purpose of initialization. These are:
1. Default Constructor: A default constructor is a constructor that takes no arguments. If a class does not have any user-defined constructors, C++ compiler automatically generates a default constructor. This constructor initializes the data members of the class with default values.
Example:
public:
int x;
MyClass() {
x = 0; // default initialization
}
};
2. Parameterized Constructor: A parameterized constructor is a constructor that takes one or more arguments. It is used to initialize the data members of the class with specific values passed as arguments.
Example:
public:
int x;
MyClass(int n) {
x = n; // initialization with argument value
}
};
3. Copy Constructor: A copy constructor is a constructor that takes an object of the same class as an argument. It is used to create a new object that is a copy of the existing object.
Example:
public:
int x;
MyClass(const MyClass &obj) {
x = obj.x; // copy data member value from obj
}
};
4. Constructor Overloading: Constructor overloading is a technique that allows a class to have multiple constructors with different parameters. It is used to provide flexibility in object initialization.
Example:
public:
int x;
MyClass() {
x = 0; // default initialization
}
MyClass(int n) {
x = n; // initialization with argument value
}
};
A destructor is a special member function of a class that gets called automatically when an object is destroyed or goes out of scope. Its primary purpose is to release the resources that were allocated by the object during its lifetime.
Example:
public:
int *ptr;
MyClass() {
ptr = new int;
}
~MyClass() {
delete ptr; // release memory allocated by object
}
};
No comments:
Post a Comment
If you have any doubts, please let me know