- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Default Constructors in C++
Constructors are functions of a class that are executed when new objects of the class are created. The constructors have the same name as the class and no return type, not even void. They are primarily useful for providing initial values for variables of the class. The two main types of constructors are default constructors and parameterized constructors.
Default constructors do not take any parameters. If a default constructor is not provided by the programmer explicitly, then the compiler provides a implicit default constructor. In that case, the default values of the variables are 0.
A program that demonstrates default constructors is given as follows.
Example
#include <iostream> using namespace std; class DemoDC { private: int num1, num2 ; public: DemoDC() { num1 = 10; num2 = 20; } void display() { cout<<"num1 = "<< num1 <<endl; cout<<"num2 = "<< num2 <<endl; } }; int main() { DemoDC obj; obj.display(); return 0; }
Output
num1 = 10 num2 = 20
In the above program, the class DemoDC contains a default constructor that initialises num1 and num2 as 10 and 20. It also contains a function display() that prints the value of num1 and num2. The code snippet for this is given as follows.
class DemoDC { private: int num1, num2 public: DemoDC() { num1 = 10; num2 = 20; } void display() { cout<<"num1 = "<< num1 <<endl; cout<<"num2 = "<< num2 <<endl; } };
The function main() contains the object definition for an object of class type DemoDC. Then the function display() is called. This is shown below.
DemoDC obj; obj.display();