Create a constructor with default arguments in C++

By IncludeHelp Last updated : November 04, 2023

In C++, you can provide the default values /arguments to the data members by using the default arguments while defining the constructor of the class.

Problem statement

Write a C++ program to create a constructor with default arguments.

Algorithm

  • Define a class with some data members.
  • Create a constructor and define the default values using the default arguments.
  • 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 default arguments.

Example

Consider the below example to create a constructor with default arguments in C++.

#include <iostream>
using namespace std;

// defining class
class Student {
 private:
  // data members
  int english, math, science;

 public:
  // constructor with default arguments
  Student(int english = 0, int math = 0, int science = 0) {
    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);
  Student std3(65, 90);
  Student std4(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;

  cout << "std3..." << endl;
  std3.getValues();
  cout << "Total marks: " << std3.getTotalMarks() << endl;
  cout << "Percentage: " << std3.getPercentage() << endl;
  cout << endl;

  cout << "std4..." << endl;
  std4.getValues();
  cout << "Total marks: " << std4.getTotalMarks() << endl;
  cout << "Percentage: " << std4.getPercentage() << endl;
  cout << endl;

  return 0;
}

Output

English marks: 0
Math marks: 0
Science marks: 0
Total marks: 0
Percentage: 0

std2...
English marks: 65
Math marks: 0
Science marks: 0
Total marks: 65
Percentage: 21.6667

std3...
English marks: 65
Math marks: 90
Science marks: 0
Total marks: 155
Percentage: 51.6667

std4...
English marks: 65
Math marks: 90
Science marks: 92
Total marks: 247
Percentage: 82.3333

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.