CONSTRUCTOR IN C++ - CONCEPT OF CONSTRUCTOR EXPLAINED- Part-29 C++. @Let's Create new #coding #cpp .

39 Просмотры
Издатель
Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object which is why it is known as constructors.

Constructor does not have a return value, hence they do not have a return type.

The prototype of Constructors is as follows:

class-name (list-of-parameters);
Constructors can be defined inside or outside the class declaration:-


The syntax for defining the constructor within the class:

class-name (list-of-parameters) { // constructor definition }
The syntax for defining the constructor outside the class:

class-name: :class-name (list-of-parameters){ // constructor definition}
Example


// defining the constructor within the class

#include iostream
using namespace std;

class student {
int rno;
char name[10];
double fee;

public:
student()
{
cout "Enter the RollNo:";
cin rno;
cout "Enter the Name:";
cin name;
cout "Enter the Fee:";
cin fee;
}

void display()
{
cout endl rno "\t" name "\t" fee;
}
};

int main()
{
student s; // constructor gets called automatically when
// we create the object of the class
s.display();

return 0;
}
Output
Enter the RollNo:Enter the Name:Enter the Fee:
0 6.95303e-310
Example

// defining the constructor outside the class

#include iostream
using namespace std;
class student {
int rno;
char name[50];
double fee;

public:
student();
void display();
};

student::student()
{
cout "Enter the RollNo:";
cin rno;

cout "Enter the Name:";
cin name;

cout "Enter the Fee:";
cin fee;
}

void student::display()
{
cout endl rno "\t" name "\t" fee;
}

int main()
{
student s;
s.display();

return 0;
}
Output:

Enter the RollNo: 30
Enter the Name: ram
Enter the Fee: 20000
30 ram 20000
Категория
Язык программирования C++
Комментариев нет.