EGR126_Ch8 - EGR 126 Computer Programming for Engineers...

This preview shows page 1 - 9 out of 41 pages.

EGR 126: ComputerProgramming for EngineersChapter 8Programmer-defined types, classesDesign & implementation of classes
Programmer-defined typesThe programming concepts and features thatwe have covered up to this point are notunique to C++. They apply to almost all high-level languages.We now move to advanced features of C++that are available only in newer languagesthat support object oriented programming.The most important object orientedprogramming concept is the use of classesorprogrammer-defined types.Recall the built-in types: int, double, char,bool.
In object oriented programming, we can alsodefine specific operations (“methods”) that canbe performed on the new classes or types.For example, we can define the subtractionoperation as calculating the distance betweentwo points.The implementation of programmer definedtypes or classes is similar to creating your ownlibrary of functions:- The declaration of the new class is placed ina header (.h) file. Don’t forget the #includestatement in the main function!- The implementation (library of methods) fileis a separate .cpp file.
Example: Point classDeclare new class in header file “Point.h”:class Point{// Declaration of attributesprivate:double xCoord, yCoord;// Function prototypespublic:double getX() const; // Returns x valuedouble getY() const; // Returns y valuevoid setX(double newX);void setY(double newY);// Distance between two pointsdouble operator - (const Point& p2)const;};
Class declaration Point.h: line by lineclass PointDeclare new classes using the keyword class.private:double xCoord, yCoord;This is analogous to declaring variables in afunction. In a class, they are called attributes.These are made private so that only functionsor methods in the Point class can access themby name. If we create a new class, we won’tbe able to specify values for xCoord andyCoord.
so
.
Class declaration Point.h: line by lineThe methods that lets us set values of theattributes xCoord and yCoord are calledmutator methods: setX() and setY().double operator - (const Point& p2)const;

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture