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.
#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; }
Total : 35To download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions