C++ 23: Constructors
Constructors are used to initialize an object. That means to store values into an object as soon as object is created. Constructors are automatically called for each object as soon as the object is created.
Characteristics :
- Constructor have same name as class name.
- Constructor not have any return type and it can return any value.
- If return type is provided to constructor then it will cause compile time error.
- Constructor is automatically called when object is created.
- The constructor is used to initialize an object so it means that to store value in the object as soon as the object is created.
- Constructor can have zero or more arguments.
- Constructor with no arguments is called as default constructor.
- Constructor having one or more arguments is called as parametrized constructor.
- It is possible to overload constructor.
- It is possible to specify default arguments with constructors.
- Constructors never inherit in derived class.
Example
WAP to check weather the constructor initialize or not.
#include <iostream>
using namespace std;class Circle{private: int R;
public: Circle() //Constructor { cout << "This is a constructor...." << endl; R = 1; }
void showdata() { cout << "Value of a is : " << R << endl; }};
main(){ Circle a, b, c; a.showdata(); b.showdata();}
Output:
This is a constructor....
This is a constructor....
This is a constructor....
Value of a is : 1
Value of a is : 12. Parameterized Contructors:
#include <iostream>
using namespace std;class Circle{private: int R;
public: Circle(int r) { R = r; } void showRadi() { cout << "Radious of circle is : " << R << endl; }
void area() { float a = 3.14 * R * R; cout << "Area of Circle is " << a << endl; } void circumference() { float c = 2 * 3.14 * R; cout << "Circumference of Circle is " << c << endl; }};
int main(){
Circle a(5); a.showRadi(); a.area(); a.circumference();
return 0;}Output:
Radious of circle is : 5
Area of Circle is 78.5
Circumference of Circle is 31.4
Example 2:
#include <iostream>
using namespace std;class Student{private: int RN; char D[10]; char N[20];
public: Student(int rn, char n[], char dp[]) { RN = rn; strcpy(D, dp); strcpy(N, n); } void showdata() {
cout << "\nRoll Number = " << RN << endl; cout << "Student Name = " << N << endl; cout << "Department = " << D << endl; }};int main(){
Student a(101, "Ayush", "CSE"); a.showdata();
Student b(100, "Sam", "IT"); b.showdata();
return 0;}Output:
Roll Number = 101
Student Name = Ayush
Department = CSE
Roll Number = 100
Student Name = Sam
Department = ITMore Examples:

Comments
Post a Comment