ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Conversion Constructor In C++ with Example

Updated on June 14, 2016
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 Yrs. I like playing video games & reading books.

1. What is Conversion Constructor?

In this Article, I will show how do we use constructor as converters. We can say a constructor as converter when the constructor is having a single argument. For Example look at the below Code:

Source

The constructor for Train accepts Boat as a parameter. Note that this constructor has only one argument and hence it can act as a converter also. The conversion is from Boat to Train. In this article, we will see an example that makes use of this Conversion Constructor. Let us go with the Example:

2. Private Members

The class DivBy5 has two members. The purpose of this class is to keep the divided and remaining portion of a number when it will be divided by Five. The member variables divided and remaining will hold the result of the division by five. Below are the members:

	//Sample 01: Private Members
private:
	int divided;
	int remaining;

3. Member Functions

DivBy5 class supports two member functions are called GetReminder and GetDivided. These two functions return the corresponding private members of the class DivBy5. The code is shown below:

//Sample 02: Member function returns the 
//			 reminder of the division
int GetReminder()
{
	return remaining;
}

//Sample 03: Get the Divident
int GetDivided()
{
	return divided;
}

4. Conversion Constructor

As Already told a class with a single parameter can be used as conversion. The constructor shown below takes a single integer as a parameter and constructs the class object of type DivBy5. When nothing is passed to the constructor the member contains the value zero. When we pass some integer number the dividend is stored in the divided member and remaining is stored in the other member of the class object.

The division operator is applied to the supplied number to get the divided value. And the Modulus (%) operator is used to hold the remainder. These two operators, I mean the division (/) and the Modulus (%) are used when we have a valid number supplied to the constructor.

Below is the code:

//Sample 04: A constructor with One Argument
//			 can be used for conversion.
DivBy5(int Number = 0)
{
	if (Number == 0)
	{
		divided = 0;
		remaining = 0;
	}
	else
	{
		divided = Number / 5;
		remaining = Number % 5;
	}
}

5. Usage

In the First Code snippet (//Sample 05) we used the constructor normally. That is we create the object by passing the integer value to it like DivBy5 Obj(22). The result of executing the first code snippet is shown below:

Source
//Sample 05: Get the division 22/5
DivBy5 Obj(22);
cout<< "Divided : " << Obj.GetDivided() 
	<< "\tReminder: " << Obj.GetReminder() << endl;

In the second code snippet, the single parameter constructor is used as Conversion Constructor by using the statement like DivBy5 Obj2 = 33; The statement looks like that a copy constructor for the DivBy5 is invoked. By looking at the left side of the assignment statement we know that the Object Obj2 is not yet constructed. But, right side is not an object of type DivBy5 and Hence the copy constructor will not be invoked. The right side of the = operator is an integer constant 33. By combining the left and right side of the operator = (Left side Object is to be constructed, right side is an integer) we can clearly say that constructor that takes the integer as a parameter will be invoked. Below is the code snippet and result of it:

Source
//Sample 06: Get the division 33/5 
// This time conversion is applied
DivBy5 Obj2 = 33;
cout<< "Divided : " << Obj2.GetDivided() 
	<< "\tReminder: " << Obj2.GetReminder() << endl;

This is a simple example to demonstrate the concept. Think of a CTime class taking an integer as Seconds and filling the parts of time class like Hour, Minute, Seconds. Ok, I am leaving it to the readers to implement it and below is the complete code Example for this Hub Page Article:

// TestIt.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class DivBy5
{
	//Sample 01: Private Members
private:
	int divided;
	int remaining;

public:
	//Sample 02: Member function returns the 
	//			 reminder of the division
	int GetReminder()
	{
		return remaining;
	}

	//Sample 03: Get the Divident
	int GetDivided()
	{
		return divided;
	}

	//Sample 04: A constructor with One Argument
	//			 can be used for conversion.
	DivBy5(int Number = 0)
	{
		if (Number == 0)
		{
			divided = 0;
			remaining = 0;
		}
		else
		{
			divided = Number / 5;
			remaining = Number % 5;
		}
	}

};

int main()
{
	//Sample 05: Get the division 22/5
	DivBy5 Obj(22);
	cout<<endl;
	cout<<endl;
	cout<< "Divided : " << Obj.GetDivided() 
		<< "\tReminder: " << Obj.GetReminder() << endl;

	//Sample 06: Get the division 33/5 
	// This time conversion is applied
	cout<<endl;
	cout<<endl;
	DivBy5 Obj2 = 33;
	cout<< "Divided : " << Obj2.GetDivided() 
		<< "\tReminder: " << Obj2.GetReminder() << endl;
}

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      reza mohajer 

      5 years ago

      so so so useful!

      thank you!

    • profile image

      Rwik Mukhopadhyay 

      5 years ago

      Great article

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)