C++ - Operator Overloading


Advertisements

Previous Page Next Page

A constructor is a special member function of a class which automatically executed when a new object of the class is created. It allows the class to initialize member variables and allocate memory.

The constructor function is declared just like a regular member function except the class name and function name should be same without any return type.

Example:

In the below example, a class called Circle is created. A constructor is also created which is used to initialize the member variable called radius of the same class.

#include <iostream>
using namespace std;
 
class Circle
 {
   public:
     int radius;
     float area()
     {
        return 22/7.0*radius*radius;
     }
     Circle(int);
 };

Circle::Circle(int x)
 {
   radius = x;
 }

int main (){
    Circle Circle_1(5);
    Circle Circle_2(10);

    cout<<Circle_1.area()<<"\n";
    cout<<Circle_2.area()<<"\n"; 
    return 0;
}

Output

78.57
314.3

Constructor Overloading


Previous Page Next Page