Constructor 11
Constructor 11
program
GANAVI V R
1MJ22EC051
L ‘ section
CONTRUCTOR :
A constructor is a special member function within a
class that is automatically called when an object of
that class is created. Its primary purpose is to
initialize the object’s data members or perform
other setup tasks necessary for the object to be in a
valid state. Have the same name as the class and do
not have a return type.
• Types of constructors :
1. Default constructor
2. Parameterized constructor
3. Overloaded constructor
4. Copy constructor
• Default constructor : A default constructor is a special constructor that is automatically generated by the
compiler if a class does not have any constructors defined explicitly. The default constructor has no
parameters and is responsible for initializing the object’s attributes to default or zero values .
• Example :
• #include <iostream>
• class MyClass {
• public:
• // Default constructor
• MyClass() {
• // Initialize attributes
• x = 0;
• y = 0;
• }
• // Member function to display coordinates
• void display() {
• std::cout << “x: “ << x << “, y: “ << y << std::endl;
• }
• private:
• int x;
• int y;
• };
• int main() {
• // Create an object of MyClass using the default constructor
• MyClass myObject;
Parameterized constructor : A parameterized constructor is a constructor that accepts one or more parameters as input when
an object of a class is created. Unlike the default constructor, which has no parameters and initializes the object with default
values, a parameterized constructor allows you to initialize the object with specific values based on the arguments provided
during object creation.
Example:
#include <iostream>
class MyClass {
public:
// Parameterized constructor
MyClass(int initialX, int initialY) {
x = initialX;
y = initialY;
}
// Member function to display coordinates
void display() {
std::cout << “x: “ << x << “, y: “ << y << std::endl;
}
private:
int x;
int y;
};
int main() {
// Create an object of MyClass using the parameterized constructor
MyClass myObject(5, 10);
// Call the display function to show the initialized values
myObject.display()
return 0;
THANKYOU