Default Constructor in C++ Programming


Constructors are special function named after the class and without a return type, and are used to construct objects. Constructors, like function, can take input parameters. Constructors are used to initialize objects.

Constructors are different from function:

  • Constructors must be named the same as the class name.
  • Constructor is automatically called when object(instance of class) is created.
  • Constructors do not have a return type

Types of constructor :

  • Default constructor
  • Parametrized constructor
  • Copy constructor
  • Constructor Overloading

The program defines a class named math which has private data members a, b, and c, and a public member function add(). The math() function is a default constructor that initializes the private data members a and b to 0.

The add() function calculates the sum of the private data members a and b, and stores it in the private data member c. It then outputs the total sum to the standard output using cout.

In the main() function, an object of the math class is created using the default constructor. The add() member function of themath class is then called on the object to calculate and display the sum of a and b.

Overall, this program provides an example of using a default constructor in C++ to initialize the private data members of a class object. The program demonstrates the use of a default constructor as a special member function of a class which is executed automatically whenever an object of the class is created.

Source Code

#include<iostream>
using namespace std;
/*
    Default Constructor
    Parameterized Constructor
    Copy Constructor
*/
//Default Constructor in C++ Programming
/*
 
A constructor in C++ is a special ‘MEMBER FUNCTION’
having the same name as that of its class which is
used to initialize some valid values to the data members
of an object. It is executed automatically whenever an
object of a class is created.
 
*/
 
class math
{
private:
    int a,b,c;
public:
    math()
    {
        a=0;
        b=0;
    }
    void add()
    {
        c=a+b;
        cout<<"Total : "<<c;
    }
};
int main()
{
    math o;
    o.add();
    return 0;
}
 
 

Output

Total : 0
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples