A constructor is a class function with the same name as the class itself. It cannot have a return type and may accept parameters. It will be called after the memory allocation to the member variables. Constructor is used to set initial values to members variables.
Example:
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class Student
{
public:
Student()
{
m_nAge=0;
strcpy(m_szName,"");
};
int m_nAge;
char m_szName[20];
};
int main()
{
Student obj;
cout<<"Name: "<<obj.m_szName<<"\r\n"<<"Age: "<< obj.m_nAge<<"\r\n";
getch();
return 0;
}
Result:
Name:
Age: 0