Tuesday , 24 November 2020
Breaking News

Constructors in C++ with Examples


Notice: Undefined index: tie_hide_meta in /home1/adnanonl/public_html/wp-content/themes/sahifa/framework/parts/meta-post.php on line 3

Notice: Trying to access array offset on value of type null in /home1/adnanonl/public_html/wp-content/themes/sahifa/framework/parts/meta-post.php on line 3
Spread the love

Constructors in C++ with Examples

Constructor in C ++. Constructors have the same name as the class, do not return any value and can not be inherited. In addition they must be public, it would not make any sense to declare a constructor as private, since they are always used from outside the classroom, nor as protected, since it can not be inherited.
Example of constructor in a class called partner
#include <iostream.h>
class couple
{
public:
//Builder
couple (int a2, int b2);
// Functions members of the class “couple”
void Lee (int & a2, int & b2);
void Save (int a2, int b2);
private:
// Data members of the class “couple”
int a, b;
}
couple :: couple (int a2, int b2)
{
a = a2;
b = b2;
}
void couple :: Lee (int & a2, int & b2)
{
a2 = a;
b2 = b;
}
void couple :: Guarda (int a2, int b2)
{
a = a2;
b = b2;
}
int main (int argc, char * argv [])
{
couple par1 (12, 32);
int x, y;
par1.Lee (x, y);
cout << “Value of par1.a:” << x << endl;
cout << “Value of par2.b:” << x << endl;
return 0;
}
Builders overload
You can also define several constructors for each class, that is, the constructor function can be overloaded. The only limitation is that you can not declare multiple constructors with the same number and the same type of arguments.

Builder copy
A constructor of this type creates an object from another existing object. These constructors have only one argument, which is a reference to an object of the same class.

Above is a video tutorial from which you can understand the basic concept of constructors in C++.

Leave a Reply

Your email address will not be published. Required fields are marked *