Home » C++ programming language

What is the Constructor and its types in C++?



Learn: What is the constructor in C++ programming language? Types of constructors in C++, Explain constructors with examples.

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.

Constructor is used for:

  • To initialize data member of class: In the constructor member function (which will be declared by the programmer) we can initialize the default vales to the data members and they can be used further for processing.
  • To allocate memory for data member: Constructor can also be used to declare run time memory (dynamic memory for the data members).

There are following properties of constructor:

  • Constructor has the same name as the class name. It is case sensitive.
  • Constructor does not have return type.
  • We can overload constructor, it means we can create more than one constructor of class.
  • We can use default argument in constructor.
  • It must be public type.

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;
}

Output

Value of X :  5
Value of X :  10

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

Note:
If we do not create constructor in user define class. Then compiler automatically insert constructor with empty body in compiled code.






Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.