Oopm Ex-5
Oopm Ex-5
Theory:
A constructor is a special member function of a class that is automatically invoked whenever an
object of that class is created. Its primary purpose is to initialize the object's data members.
Types of Constructors:
1. Default Constructor:
o Declared without any parameters.
o Automatically provided by the compiler if no user-defined constructor is present.
o Initializes members to their default values.
C++
class MyClass {
public:
MyClass() {
// Initialize members here
}
};
2. Parameterized Constructor:
o Accepts one or more parameters to initialize members.
o Allows flexible object creation with different initial values.
C++
class MyClass {
1|Page
public:
MyClass(int x, double y) {
// Initialize x and y members
}
};
3. Copy Constructor:
o Accepts an object of the same class as a reference parameter.
o Used to create a copy of an existing object.
C++
class MyClass {
public:
MyClass(const MyClass& obj) {
// Copy members from obj to this object
}
};
Key Points to Remember:
A constructor cannot be inherited.
A constructor cannot be virtual.
A constructor cannot be static.
A constructor is called implicitly when an object is created.
A constructor can be overloaded.
A constructor can be private.
By understanding these concepts, you can effectively use constructors to initialize objects in C++
and ensure proper object creation.
Program:
Default Constructor--
#include<iostream>
using namespace std;
class area{
int a=10,b=20;
public:
area(){
cout<<"Area of wall is: "<<a*b;
}
};
2|Page
int main(){
area obj;
}
Parameterized Constructor--
#include<iostream>
using namespace std;
class area{
int l,b;
public:
area(int l,int b){
int x=l;
int y=b;
cout<<"Area of wall is: "<<x*y;
}
};
int main(){
int x,y;
cout<<"Enter length of wall: ";
cin>>x;
cout<<"Enter width of wall: ";
cin>>y;
area a1(x,y);
return 0;
}
Copy Constructor--
#include<iostream>
using namespace std;
class area
{
public:
int l,w;
area(int a,int b)
{
l=a;
w=b;
}
area(area &ref){
l=ref.l;
w=ref.w;
}
void display()
{
3|Page
cout<<"Area of wall is: "<<l*w;
}
};
int main()
{
area obj1(10,20);
area obj2=obj1;
obj2.display();
}
Output:
Default Constructor--
Area of wall is: 200
Parameterized Constructor--
Enter length of wall: 10
Enter width of wall: 20
Area of wall is: 200
Copy Constructor--
Area of wall is: 200
1. What is constructor?
4|Page
3. Why we use constructor?
5|Page