Use automatic conversions to assign new values : Constructor « Class « C++






Use automatic conversions to assign new values

Use automatic conversions to assign new values
  
#include <iostream>
#include <cstdlib>
using namespace std;

class myclass {
  int a;
public:
  myclass(int x) { 
     a = x; 
  } 
  myclass(char *str) { 
     a = atoi(str); 
  }
  int geta() { 
     return a; 
  }
};
 
int main()
{
  myclass object1 = 4;     // converts to myclass(4)
  myclass object2 = "123"; // converts to myclass("123");

  cout << "object1: " << object1.geta() << endl;
  cout << "object2: " << object2.geta() << endl;

  
  object1 = "1776";        // converts into object1 = myclass("1776");
  object2 = 2001;          // converts into object2 = myclass(2001);

  cout << "object1: " << object1.geta() << endl;
  cout << "object2: " << object2.geta() << endl;

  return 0;
}



           
         
    
  








Related examples in the same category

1.Constructing and Destructing sequence for three level inheritance
2.Parameterized ConstructorsParameterized Constructors
3.string type constructorstring type constructor
4.Use constructor to init member variablesUse constructor to init member variables
5.Use Double value as the constructor parameterUse Double value as the constructor parameter
6.Constructor: different parameter typeConstructor: different parameter type
7.Call constructor from base classCall constructor from base class
8.Constructor with 2 parametersConstructor with 2 parameters
9.Define constructor outside a class definition
10.overloading class constructors
11.Constructor with parameter value checking