Class Declaration and Using Constructor with Different Arguments | Starting Up with C++ Constructors
In C++, a Constructor is a Special Method that is called automatically when we create the object of the. Constructor is created with the same name as the Class Name and is followed by parentheses ().
Constructor also takes parameters just as the functions, which are used for setting values for attributes. Constructors can be defined Inside as well as Outside the Class. For defining the Constructor outside the class, first Declare the Constructor inside the class, and then define it outside by specifying the name of the Class, followed by Scope Resolution Operator.
Here is the example for Constructor
Example 1 : Declare Class and use Constructor with Different Arguments
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
class Value
{
private:
int a;
float b;
char *info;
public:
Value()
{
cout << “Constructor Without Parameters “ << endl;
cout << endl;
a = 0;
b = 0.0;
info = “ “;
}
Value(int, float, char *);
void display();
};
Value ::Value(int m, float n = 300, char *ptr = “Ram”)
{
cout << “Constructor Called With Parameters” << endl;
cout << endl;
a = m;
b = n;
info = ptr;
}
void Value ::display()
{
cout.precision(2); //Store the value of fixed size till the Function Ends
cout << “Integer Value is : “ << a << endl;
cout << “Float Value is : “ << b << endl;
cout << “Character Value is : “ << info << endl;
}
void main()
{
clrscr();
char *str = “My Name is Ram”;
Value e; //Object Created without Parameter therefore, Constructor without Parameter will be Called
e.display();
Value c(10, 5.7, str); //Object Created with Parameter therefore, Constructor with Parameter will be Called
c.display();
Value d(20, 50.32, “Your Name”);
d.display();
getch();
}
Points from Program :
// It is Not possible to have constant value for all Arguments.
In Above Example you saw a basic program to store the value through parameter in Constructor and display it with the help of Function.
Originally published at https://aapkacoder.blogspot.com on March 11, 2021.