Classes and OOP
Classes and OOP
MotivationBasic, built-in, pre-defined types: char, int, double, ..Variables+operationsonthemint a, b,c;C=a+b;c=amod b;More complicated,user-definedtypes:classesVariables→objectsTypesclasses
Basic, built-in, pre-defined types: char, int, double, . Variables + operations on them int a, b,c; c=a+b; c=a mod b; . More complicated, user-defined types: classes Motivation Variables → objects Types → classes
MotivationTypes such as int, double, and char aresimple(and“stupid")objectsThey can only answer one question:"Whatvaluedo you contain?"3!!!
Motivation Types such as int, double, and char are simple (and “stupid”) objects. They can only answer one question: “What value do you contain?” 3!!!
MotivationWe want to build user-defined (and "smart")objects that can answer many questions (andperform various actions)“"What is your temperature?""What is yourtemperature in Fahrenheit?""What is your humidity?"“"Printyourtemperature inCelsius."Whatisyourwish?
Motivation We want to build user-defined (and “smart”) objects that can answer many questions (and perform various actions). “What is your temperature?” “What is your temperature in Fahrenheit?” “What is your humidity?” “Print your temperature in Celsius.” What is your wish?
Temperature exampleWrite a program that, given a temperature in Fahrenheit orCelsius, will display the equivalent temperature in each ofthe scales.double degree= 0.O;needs 2 items!char scale = 'F';To apply a function f () to atemperature,we must specifyboth degree andscale:f(degree, scale);cal eather Forecas8200Camtonese)Alsotodisplayatemperature:8202(Putonghua)cout<< degree<<scale;1878066(English)
Temperature example Write a program that, given a temperature in Fahrenheit or Celsius, will display the equivalent temperature in each of the scales. double degree = 0.0; // needs 2 items! char scale = 'F'; To apply a function f() to a temperature, we must specify both degree and scale: f(degree, scale); Also to display a temperature: cout << degree << scale;