Home »
C+ Programs »
C++ Constructor, Destructor Programs
Create a class with two constructors in C++
By IncludeHelp Last updated : November 04, 2023
In C++, a class may have more than one constructor function with different parameter lists with respect to the number and types of arguments. The concept of multiple constructors in a class is known as Constructor overloading.
Problem statement
Write a C++ program to create a class with two constructors.
Steps to create a class with two constructors
- Define a class with some data members.
- Create two constructors. In the below example, we are defining two constructors one is without parameters and the second one is with the parameters.
- Create member functions to perform operations on the data members.
- Inside the main function, create objects by passing the different number of arguments to test the functionality of the concept of constructor overloading.
C++ program to create a class with two constructors
Consider the below example to create a class with two constructors in C++.
#include <iostream>
using namespace std;
// defining class
class Student {
private:
// data members
int english, math, science;
public:
// constructor without parameters
Student() { english = math = science = 0; }
// constructor with parameters
Student(int english, int math, int science) {
this->english = english;
this->math = math;
this->science = science;
}
// member functions
// To display values
void getValues() {
cout << "English marks: " << english << endl;
cout << "Math marks: " << math << endl;
cout << "Science marks: " << science << endl;
}
// To return total marks
int getTotalMarks() { return english + math + science; }
// To return total marks
float getPercentage() { return ((float)getTotalMarks() / 300 * 100); }
};
int main() {
// Create objects
Student std1;
Student std2(65, 90, 92);
// Display the values, calculate and display the
// total marks and Percentage
cout << "std1..." << endl;
std1.getValues();
cout << "Total marks: " << std1.getTotalMarks() << endl;
cout << "Percentage: " << std1.getPercentage() << endl;
cout << endl;
cout << "std2..." << endl;
std2.getValues();
cout << "Total marks: " << std2.getTotalMarks() << endl;
cout << "Percentage: " << std2.getPercentage() << endl;
cout << endl;
return 0;
}
Output
std1...
English marks: 0
Math marks: 0
Science marks: 0
Total marks: 0
Percentage: 0
std2...
English marks: 65
Math marks: 90
Science marks: 92
Total marks: 247
Percentage: 82.3333