// An example of programming using user defined types #include <iostream> // Here is the type definition, that is a declaration // containing the type data layout and the operations // needed to use the type in the correct way. // The type is created using a class, that is a type that // implement a separation between a public part, what every // user can use, and a private part, what can be used only // by object of the type itself. class ave{ public: // Here the modules, functions, needed to create an object in memory // And operate on the data layout ave & operator+=(int d){ rsum_+=d; ncount_++; double stemp=static_cast<double>(rsum_); double ntemp=static_cast<double>(ncount_); amean_=stemp/ntemp; return *this; } double get_ave() const { return amean_;} private: // Here the list of data needed to describe // the type. int ncount_{0}; int rsum_{0}; double amean_{0.}; }; // Every C++ program must start executing a function called main. int main(){ // User's types have the same support of the base types // Create an object with a state, i.e. data layout, and // a behavior, i.e. the code needed to manage the data layout, // connected somehow in memory. ave a; int indata{0}; std::cout <<"Enter values [Ctrl-D to finish]: " <<std::endl; // The object oriented programming semantic is implemented in C++ using // operators, that is symbols that represent an operation. Here std::cin and a // are the "object"s to operate on ... while(std::cin>>indata){ a+=indata; } // ... here the std::cout is the "object" to "use" std::cout << "Average: " << a.get_ave() << std::endl; return 0; }