This lab experiment demonstrates the implementation and use of different types of constructors in C++. Constructors are special member functions that are automatically called when an object of a class is created.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. It initializes the object with standard or default values.
#include<iostream>
#include<string>
using namespace std;
class Product{
private:
int ProductID;
string ProductName;
float price;
public:
// Default constructor
Product() {
ProductID = 6082026;
ProductName = "Unknown";
price = 0.00;
}
void display() {
cout << "Product ID: " << ProductID << endl;
cout << "Product Name: " << ProductName << endl;
cout << "Product Price: " << price << endl;
}
};
int main() {
Product P1;
P1.display();
return 0;
}A parameterized constructor takes arguments to initialize an object with specific values. A copy constructor initializes an object using another object of the same class.
#include<iostream>
using namespace std;
class BOX{
private:
int length;
int breath;
int height;
public:
// Parameterized constructor -
BOX(int l, int b, int h) {
length = l;
breath = b;
height = h;
}
void displayVolume() {
cout << "Volume: " << length*breath*height << endl;
}
};
int main
A class can have multiple constructors (Constructor Overloading). Here is an example of a class having both a default and a parameterized constructor.
#include<iostream>
#include<string>
using namespace std;
class Movie{
private:
string name;
float rating;
public:
// Default constructor
Movie() {
name = "Unknown";
rating = 0.00;
}
// Parameterized constructor -
Movie(string Name, float Rating) {
name = Name;
rating = Rating;
}
void display() {
cout << "Name: " << name << endl;
cout
A constructor that takes no arguments and initializes object attributes to default values.
A constructor that takes arguments to initialize an object with specific values upon creation.
A constructor that initializes an object using another object of the same class.
Test your understanding with 2 questions
Which of the following constructors takes no parameters?
How is a copy constructor called?
2 Modules
2 Modules