Constructor overloading in C++Constructor is a member function of a class that is used to initialize the objects of the class. Constructors do not have any return type and are automatically called when the object is created. Characteristics of constructors
Types of constructorsThere are three types of constructors -
Code Output a:10 b:20
Code Output p1.x = 10, p1.y = 15 Explanation Create a class point with two data members x and y. A parameterized constructor is created with the points x1 and y1 as parameters and the value of x and y are assigned using x1 and y1. In the main function, we create a parameterized constructor with the values (10, 15). Using the getter functions, we get the values of the data members.
Syntax class_name(constclassname&old_object). Code Output p1.x = 10, p1.y = 15 p2.x = 10, p2.y = 15 Constructor overloading in C++As there is a concept of function overloading, similarly constructor overloading is applied. When we overload a constructor more than a purpose it is called constructor overloading. The declaration is the same as the class name but as they are constructors, there is no return type. The criteria to overload a constructor is to differ the number of arguments or the type of arguments. Code Explanation In the above program, we have created a class Person with one data member(age). There are two constructors in the class that are overloaded. We have overloaded the second constructor by providing one argument and making it parameterized. So, in the main function when the object person1 is created, it calls the non-parameterized constructor and when person2 is created, it calls the parameterized constructor and performs the required operation of initializing the age. Hence, when object person1 age is printed it gives 20 that was set by default and person2 age gives 45 as it was passed by the object to the parameterized constructor.
Next TopicDefault arguments in C++
|