Assignment versus Initialization in C ++

I thought that the constructors control the initialization and control assignment of operator = functions in C ++. So why does this code work?

#include <iostream> #include <cmath> using namespace std; class Deg { public: Deg() {} Deg(int a) : d(a) {} void operator()(double a) { cout << pow(a,d) << endl; } private: int d; }; int main(int argc, char **argv) { Deg d = 2; d(5); d = 3; /* this shouldn't work, Deg doesn't have an operator= that takes an int */ d(5); return 0; } 

In the third line of the main function, I assign an int object of class Deg . Since I don't have an operator=(int) function, I thought that of course it would fail ... but instead, it calls the Deg(int a) constructor. So do designers also manage the assignment?

+7
c ++ initialization class operator-overloading
source share
2 answers

This is what is called implicit type conversion. The compiler will see if the constructor will directly change the type assigned to the type you want to assign and call it. You can stop it by adding the explicit keyword before a constructor that you would not like to implicitly call, for example:

explicit Deg(int a) : d(a) {}

+18
source share

Just to clarify JonM's answer:

For the string d = 3 , the assignment operator is used. . 3 implicitly converted to Deg , as JonM said, and then Deg is assigned to d using the assignment operator generated by the compiler (which defaults to the definition member). If you want to prevent assignment, you must declare a private assignment operator (and not execute it):

 //... private: Deg& operator=(const Deg&); } 
+4
source share

All Articles