You are on page 1of 10

Session Objectives

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

Classname and function name must be same


It should be declared inside public It has no return types It may have arguments (optional) If it does not has any arguments, it is called default constructor If it has arguments, it is called overloaded constructor So a program can have any number of constructor It cannot be Virtual

It cannot refer to their address

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++

Constructor for the class

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

You might also like