Cpp - Assign built-in type to custom object

Introduction

We will learn how to assign a built-in type to an object.

The following code creates a conversion operator: a constructor that takes an int and produces a Counter object.

Demo

#include <iostream> 
   // w ww  .  j  a v  a 2 s  . c  o  m
class Counter 
{ 
public: 
    Counter(); 
    ~Counter() {} 
    Counter(int newValue); 
    int getValue() const { return value; } 
    void setValue(int newValue) { value = newValue; } 
private: 
    int value; 
}; 
   
Counter::Counter(): 
value(0) 
{} 
 
Counter::Counter(int newValue): 
value(newValue) 
{} 
   
int main() 
{ 
    int beta = 5; 
    Counter alpha = beta; 
    std::cout << "alpha: " << alpha.getValue() << std::endl; 
    return 0; 
}

Result

The constructor is overloaded to take an int. The effect of this constructor is to create a Counter out of an int.

Given this constructor, the compiler knows to call it when an integer is assigned to a Counter object.

Related Topic