Parameterized Constructor in C++ Programming


Constructors are special function named after the class and without a return type, and are used to construct objects. Constructors, like function, can take input parameters. Constructors are used to initialize objects. The parameterized constructors are the constructors having a specific number of arguments to be passed. The purpose of a parameterized constructor is to assign user-wanted specific values to the instance variables of different objects.

Example :
      When we create the object like this Student s = Student ( " Joes " , 15 ) ;then invokes the Parameterized constructor with int and string parameters Student ( String n , int a ) after object creation.

The program defines a class named math which has private data members a, b, and c, and a public member function add(). The math(int x, int y) function is a parameterized constructor that takes two integer arguments x and y and initializes the private data members a and b with these values.

The add() function calculates the sum of the private data members a and b, and stores it in the private data member c. It then outputs the total sum to the standard output using cout.

In themain() function, an object of the math class is created using the parameterized constructor and passing the integer values 10 and 25 as arguments. The add() member function of the math class is then called on the object to calculate and display the sum of a and b.

Source Code

#include<iostream>
using namespace std;
/*
    Default Constructor
    Parameterized Constructor
    Copy Constructor
*/
//Parameterized Constructor in C++ Programming
 
class math
{
private:
    int a,b,c;
public:
    math(int x,int y)
    {
        a=x;
        b=y;
    }
    void add()
    {
        c=a+b;
        cout<<"Total : "<<c;
    }
};
int main()
{
    math o(10,25);
    o.add();
    return 0;
}
 

Output

Total : 35
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples