What is constructor explain types of constructor with example in c++?
Answers
Answered by
5
Constructor is the special type of member function in C++ classes, which are automatically invoked when an object is being created. It is special because its name is same as the class name.
Example:
#include <iostream> using namespace std; class Sample { private: int X; public: //default constructor Sample() { //data member initialization X=5; } void set(int a) { X = a; } void print() { cout<<"Value of X : "<<X<<endl; } }; int main() { //Constructor called when object created Sample S; S.print(); //set new value S.set(10); S.print(); return 0; }
Types of constructors in C++
Normally Constructors are following type:
(1) Default Constructor or Zero argument constructor
(2)Parameterized constructor
(3)Copy constructor
(4)Conversion constructor
(5)Explicit constructor
Example:
#include <iostream> using namespace std; class Sample { private: int X; public: //default constructor Sample() { //data member initialization X=5; } void set(int a) { X = a; } void print() { cout<<"Value of X : "<<X<<endl; } }; int main() { //Constructor called when object created Sample S; S.print(); //set new value S.set(10); S.print(); return 0; }
Types of constructors in C++
Normally Constructors are following type:
(1) Default Constructor or Zero argument constructor
(2)Parameterized constructor
(3)Copy constructor
(4)Conversion constructor
(5)Explicit constructor
Answered by
4
constructor can be mainly explained as a specialised method of a class which has the same name as the classroom and is used to initialise the data members in the time of object creation . Constructors does not have any return type and it is invoked automatically whenever an object of the class is created .
Similar questions