c++day-7
TRANSCRIPT
-
7/31/2019 C++Day-7
1/10
-
7/31/2019 C++Day-7
2/10
Define Constructor
parameterized Constructor
Constructor with default arguments
Constructor overloading
-
7/31/2019 C++Day-7
3/10
SyntaxClassname()
{Statements;
}
Note : Argument is optional
Constructor is a non-static special member
function which that is automatically called when anobject is created
It can be used to initalize the class members
-
7/31/2019 C++Day-7
4/10
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
-
7/31/2019 C++Day-7
5/10
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
{
--
}
-
7/31/2019 C++Day-7
6/10
C++Constructor for
the class Object
-
7/31/2019 C++Day-7
7/10
DEFAULT CONSTRUCTOR#include
#include
class exam {
private:
int sno,mark1,mark2;public:
exam( ) {
sno = mark1 = mark2 =100;
}void showdata()
{cout
-
7/31/2019 C++Day-7
8/10
Used to initialize the data members of a class with different
values when they are created. This is achieved by passingarguments to the constructor functions when the objects are created
For example:
Class emp{
Private :
int empno;
Public :emp(int eno) //Parameterized constructor
{
empno=eno;
}
-
7/31/2019 C++Day-7
9/10
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;
}
-
7/31/2019 C++Day-7
10/10
OVERLOADED CONSTRUCTOR#include
class circle{
private:
int radius;
float area;
int b,h;
public:
circle(){
cout