
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Conversion Constructor in C++
In this section we will see what is the conversion constructor in C++ class. A constructor is a special type of function of class. It has some unique property like, its name will be same as class name, it will not return any value etc. The constructors are used to construct objects of a class. Sometimes constructors may take some arguments, or sometimes it does not take arguments.
When a constructor takes only one argument then this type of constructors becomes conversion constructor. This type of constructor allows automatic conversion to the class being constructed.
Example
#include<iostream> using namespace std; class my_class{ private: int my_var; public: my_class(int x) { this->my_var = x; //set the value of my_var using parameterized constructor } void display() { cout << "The value of my_var is: " << my_var <<endl; } }; int main() { my_class my_obj(10); my_obj.display(); my_obj = 50; //here the conversion constructor is called my_obj.display(); }
Output
The value of my_var is: 10 The value of my_var is: 50
Advertisements