C++ Programming

Constructor in C++

Constructor is a special member function which is executed when an object is created.

When an object is created, C++ calls the constructor for that object. If no constructor is defined explicitly / manually in the program, then C++ creates and invokes a constructor callout default constructor which allocates memory space for object.
The general syntax to define a constructor is as under.


Constructor-name( arguments)
{
// body of constructor
}

Constructor-name' is the name of constructor. It must me as the name of the class where it is defined.

Example, suppose we have defined a class named student.


student()
{
statement 1;
statment 2;
'
'
'
}

A Programming Example of constructer

In the following Example we create a class Student with constructure which get the name and marks of student and a mimber function show().


#include<stdio.h>
#include<iostream>
using namespace std;
class student
{
	public:
		string sname;
		int marks;

	public:
		student()
		{
		cout<<"Enter Name"<<endl;
		getline(cin,sname);
		cout<<"Enter marks"<<endl;
		cin>>marks;
		cout<<endl;	
		}
		void show()
		{
		cout<<"Name"<<'\t'<<'\t'<<"Marks"<<endl;	
		cout<<sname<<'\t'<<'\t'<<marks<<endl;
		}
};

int main()
{
student info;
info.show();
return 1;
}