Define Constructor
parameterized Constructor Constructor with default arguments Constructor overloading
Constructor is a non-static special member function which that is automatically called when an object is created
It can be used to initalize the class members
Syntax
Classname(<argument>) { Statements; } Note : Argument is optional
RULES
Cannot inherited through derived class call the base class constructor
If a constructor takes no Arguments it is called No argument constructor or Default constructor This constructor has public access within the class .
For example:
Class emp { Private : int empno; Public :
emp()
{ -}
//Default constructor
C++
Object
DEFAULT CONSTRUCTOR
#include<iostream.h> #include<conio.h> class exam { private: int sno,mark1,mark2; public: exam( ) {
sno = mark1 = mark2 =100;
} void showdata() {
cout<<"Sno"<<sno <<"Mark1 <<mark1<<"Mark2<<mark2 ; }
exam(int a,int m1,int m2) { sno=a; mark1=m1; mark2=m2; }}; void main() { exam e,e1; clrscr(); e.showdata(); e.getdata(); e.showdata(); getch(); }
Used to initialize the data members of a class with different values when they are created. This is achieved by passing arguments to the constructor functions when the objects are created
For example:
Class emp { Private : int empno; Public :
emp(int eno)
{ empno=eno; }
//Parameterized constructor
It is possible to define more than one constructor function in a class. This is known as Constructor Overloading. class emp{ private : int empno; int x; public : emp(int eno) { empno=eno;} emp(int no,n) { empno=no; x=n; }
OVERLOADED CONSTRUCTOR
#include<iostream.h> class circle { private: int radius; float area; int b,h; public: circle(){ cout<<"Enter the radius "<<endl; cin>>radius; area=3.14 * radius * radius; cout<<"area of the circle"<< area; } }; circle(int r){ radius=r; area=3.14 * radius * radius; cout<< "\narea of the circle is " << area; } circle(int x,int y){ b=x; h=y; area=0.5*b*h; cout<< "\n area of the Triangle is " << area;} void main() { circle c; circle d1(6); circle c1(3,4); }