Constructors In C ++
What is constructor? Define Constructor with example
Constructor is a special member function of a class. It is used to initialize fo an instance of the class. Constructors are automatically invoked when object is created. It is different from all other member functions because it is used to initialize the variables of class.
Rules for writing Constructors:
- Constructor name same as that of class name
- It is declared with no return type. Not even void
- Constructor may not be static and virtual
- It should have public or protected access within the class
General Syntax to declare Constructor:
class class_name
{
private:
__________
__________
protected:
_________
_________
public:
class_name(); // constructor
_________
_________
};
class_name::class_name()
{
___________
____________
}
Following example illustrates constructor inside of class definition
class student
{
private:
char name[20];
int rollno[20];
public:
student() //constructor
{
___________
___________
}
void display()
{
__________
__________
}
};
Following example illustrates constructor outside of class definition
class student
{
private:
char name[20];
int rollno[20];
public:
student(); // constructor
void getdata();
void display();
};
student::student() //constructor defined outside of class
{
_________
_________ // related methods
}
C ++ program to display Fibonacci series using constructor
// Display Fibonacci series using constructor
#include<iostream.h>
#include<conio.h>
class fibonacci
{
private:
int f0, f1, f2;
public:
fibonacci() /constructor
{
f0 = 0;
f1 = 1;
f2 = f0 + f1;
}
void display()
{
f0 = f1;
f1 = f2 ;
f2 = f0+f1;
cout<<” Fibonacci Series is:”<<’\t’;
}
};
void main()
{
fibonacci obj;
// Fibonacci series number up to 50
for(int i=0 ; i<=50; i++)
{
obj.display();
}
}
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏