C++ Constructor
C++ Constructor
Raj Kumar
C++ Constructor
1. In C++, constructor is a special method which is
invoked automatically at the time of object creation.
2. It is used to initialize the data members of new object
generally.
3. The constructor in C++ has the same name as class or
structure.
4. In brief, A particular procedure called a constructor is
called automatically when an object is created in C++.
5. In C++, the class or structure name also serves as the
constructor name.
6. When an object is completed, the constructor is
called.
Characteristics of constructor functions
1. Constructors are invoked automatically when
we create objects.
2. Constructors should be declared in the public
section of the Class.
3. Constructors cannot return values to the calling
program because they do not have return types.
4. Constructors cannot be inherited because they
are called when objects of the class are created.
The Constructors prototype looks like this:
• <class-name> (list-of-parameters);
Example :-
class Wall
{
public:
Wall() // create a constructor
{ // code
}
};
C++ Constructor
1. Default Constructor
• A constructor with no arguments (or
parameters) in the definition is a default
constructor. Usually, these constructors use to
initialize data members (variables) with real
values.
• Note: If no constructor is explicitly declared, the
compiler automatically creates a default
constructor with no data member (variables) or
initialization.
1. Default Constructor
class CLASS_NAME
{
………
public :
CLASS_NAME() //Default constructor
{
......
}
Sample(Sample &t)
{
id=t.id;
}
#include<iostream>
#include<string.h>
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
student(student &t) //copy constructor (member wise initialization)
{
rno=t.rno;
strcpy(name,t.name);
}
void display();
void disp()
{
cout<<endl<<rno<<"\t"<<name;
}
};
student::student(int no, char n[],double f)
{
rno=no;
strcpy(name,n);
fee=f;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()
{
student s(1001,"Manjeet",10000);
s.display();
return 0;
}